package com.yitao.cms.service.order;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.common.excel.DataColumn;
import com.skipper.base.common.excel.DataTable;
import com.skipper.base.common.excel.ExcelConverter;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.json.JSON;
import com.skipper.base.json.JSONArray;
import com.skipper.base.json.JSONObject;
import com.skipper.base.service.GenericEntityService;
import com.skipper.base.utils.DateUtil;
import com.skipper.base.utils.HttpUtils;
import com.yitao.client.constant.*;
import com.yitao.client.dto.cashCoupons.CashCouponsInfoDto;
import com.yitao.client.dto.order.MallOrderDto;
import com.yitao.client.dto.order.MallOrderListDto;
import com.yitao.client.dto.pay.PayStreamDto;
import com.yitao.client.dto.shopInfo.ShopInfoDto;
import com.yitao.client.dto.user.UserCardNoDto;
import com.yitao.client.model.expressage.OrderLogisticTaskModel;
import com.yitao.client.model.expressage.ServicesCompanyInfoModel;
import com.yitao.client.model.order.*;
import com.yitao.client.model.pay.PayStreamModel;
import com.yitao.client.model.product.BaseProductCategoryModel;
import com.yitao.client.model.product.ProductInfoModel;
import com.yitao.client.model.product.ProductSkuModel;
import com.yitao.client.model.purchase.ProcurementOrderDetailModel;
import com.yitao.client.model.shopInfo.ShopUserGradeModel;
import com.yitao.client.model.user.UserAddressManagementModel;
import com.yitao.client.model.user.UserCardNoModel;
import com.yitao.client.model.user.UserInfoModel;
import com.yitao.cms.constant.BaseEnum;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.constant.order.LogisticsKeywordConstant;
import com.yitao.cms.constant.order.OrderEnums;
import com.yitao.cms.dto.order.OrderStreamDto;
import com.yitao.cms.exception.YiTaoCmsRuntimeException;
import com.yitao.cms.mapper.OrderMapper;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.model.order.OrderDeliveryUpdateLogModel;
import com.yitao.cms.service.cashCoupons.CashCouponsService;
import com.yitao.cms.service.constant.ConstantDataService;
import com.yitao.cms.service.expressage.Kuaidi100CmsService;
import com.yitao.cms.service.pay.CmsPayStreamService;
import com.yitao.cms.service.procurement.CmsProcurementOrderDetailService;
import com.yitao.cms.service.product.BaseProductCategoryService;
import com.yitao.cms.service.product.ProductCmsService;
import com.yitao.cms.service.product.ProductCmsSkuService;
import com.yitao.cms.service.shopInfo.CmsShopInfoService;
import com.yitao.cms.service.shopInfo.ShopUserGradeService;
import com.yitao.cms.service.user.appUser.AppUserAddressService;
import com.yitao.cms.service.user.appUser.AppUserCardNoService;
import com.yitao.cms.service.user.appUser.AppUserService;
import com.yitao.cms.utils.*;
import com.yitao.cms.vo.CategoryVo;
import com.yitao.cms.vo.LogisticsInformationVo;
import com.yitao.cms.vo.order.*;
import com.yitao.cms.vo.pay.CmsOrderPayInfoVo;
import com.yitao.cms.vo.user.appUser.AppUserAddressVo;
import com.yitao.cms.vo.user.appUser.AppUserInfoDetailsVo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.google.common.collect.Lists.newArrayList;
import static com.skipper.base.utils.DateUtil.DATE_TIME_PATTERN;

@Service
public class CmsOrderService extends GenericEntityService<MallOrderModel, MallOrderDto, QMallOrderModel> {

    private BaseUtils base = BaseUtils.getInstance();

    @Autowired
    private CmsOrderLogisticaskService cmsOrderLogisticaskService;

    @Autowired
    private ProductCmsService productCmsService;

    @Autowired
    private ProductCmsSkuService productCmsSkuService;

    @Autowired
    private BaseProductCategoryService baseProductCategoryService;

    @Autowired
    private ConstantDataService constantDataService;

    @Autowired
    private OrderDeliveryUpdateLogService orderDeliveryUpdateLogService;


    @Autowired
    private CmsOrderDetailService cmsOrderDetailService;

    @Autowired
    private CmsShopInfoService cmsShopInfoService;

    @Autowired
    private CmsOrderDeliveryService cmsOrderDeliveryService;

    @Autowired
    private CmsMallOrderLogService cmsMallOrderLogService;

    @Autowired
    private AppUserAddressService appUserAddressService;

    @Autowired
    private CmsPayStreamService cmsPayStreamService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private CmsMallOrderRefundService cmsMallOrderRefundService;

    @Autowired
    private AppUserCardNoService appUserCardNoService;

    @Autowired
    private OrderDeliveryPackageService orderDeliveryPackageService;

    @Autowired
    private CmsProcurementOrderDetailService cmsProcurementOrderDetailService;

    @Autowired
    private CmsUserOrderGradePreferentialService cmsUserOrderGradePreferentialService;

    @Autowired
    private SynchronousOrderService synchronousOrderService;

    @Autowired
    private ShopUserGradeService shopUserGradeService;

    @Autowired
    private CmsMallOrderCouponsService cmsMallOrderCouponsService;

    @Value("${app_wxPush_url}")
    private String wxPushUrl;

    @Value("${logistics_push_take}")
    private String logisticsPushTake;

    @Value("${kuaidi100}")
    private Boolean kuaidi100Status;

    @Autowired
    private OutStockRefundLogService outStockRefundLogService;

    //物流查询
    @Value("${kuaidi.customer}")
    private String customer;//= "544B760F901B9021E0EB904CC15E6604";
    @Value("${kuaidi.key}")
    private String key;//= "kWCbJSyp5378";
    @Value("${kuaidi.url}")
    private String url;//= "https://poll.kuaidi100.com/poll/query.do";
    @Value("${refund_url}")
    private String refundUrl;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CmsOrderMoneyChangeLogService cmsOrderMoneyChangeLogService;

    @Autowired
    private CmsServicesCompanyInfoService cmsServicesCompanyInfoService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private Kuaidi100CmsService kuaidi100CmsService;
    @Autowired
    private CmsOrderDeliveryDetailService cmsOrderDeliveryDetailService;

    @Autowired
    private CmsOrderDeliveryPackageInfoService cmsOrderDeliveryPackageInfoService;

    @Autowired
    private CmsOrderShopRefundLogService cmsOrderShopRefundLogService;

    @Autowired
    private CashCouponsService cashCouponsService;

    public CmsOrderService(EntityManager entityManager) {
        super(entityManager);
    }

    //查询订单列表
    public PagedOutput getOrderListByBean(PagedInput pagedInput, String orderNo, Integer searchEnum, String startTime, String endTime, Integer orderStatus, Integer payType) {
        PagedOutput<CmsMallOrderVo> orderList = new PagedOutput<CmsMallOrderVo>(pagedInput, 0L, new ArrayList<CmsMallOrderVo>());
        Date startDate = null;
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }

        if (StringUtils.isNotBlank(startTime)) {
            startDate = DateUtil.parseDate(startTime + " 00:00:00", DATE_TIME_PATTERN);
        }
        Date endDate = null;
        if (StringUtils.isNotBlank(endTime)) {
            endDate = DateUtil.parseDate(endTime + " 23:59:59", DATE_TIME_PATTERN);
        }
        CmsMallOrderVo cmsMallOrderVo = getCmsMallOrderVoByOrderStatus(orderStatus, userSession.getShopId(), startDate, endDate, orderNo, searchEnum, payType);
        return getOrderList(pagedInput, cmsMallOrderVo, true);
    }

    //订单状态查询信息构建
    private CmsMallOrderVo getCmsMallOrderVoByOrderStatus(Integer orderStatus, Long shopId, Date startDate, Date endDate, String orderNo, Integer searchEnum, Integer payType) {
        CmsMallOrderVo cmsMallOrderVo = new CmsMallOrderVo();
        List<Integer> refundStatusList = Lists.newArrayList();
        refundStatusList.add(OrderStatusEmnu.REFUND_STATUS.STANDARD_ORDER.getCode());
        refundStatusList.add(OrderStatusEmnu.REFUND_STATUS.REFUND_REJECTED.getCode());
        refundStatusList.add(OrderStatusEmnu.REFUND_STATUS.PORTION_APPLYING_FOR_REFUND.getCode());
        refundStatusList.add(OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND_OF.getCode());
        refundStatusList.add(OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND.getCode());
        refundStatusList.add(OrderStatusEmnu.REFUND_STATUS.REFUND_ERROR.getCode());
        if (orderStatus == null || OrderStatusEmnu.CmsOrderShowStatusEnum.ALL.getCode().equals(orderStatus)) {
            refundStatusList = Lists.newArrayList();
            cmsMallOrderVo.setRefundStatusList(refundStatusList);
        } else
            //查询未支付的
            if (OrderStatusEmnu.CmsOrderShowStatusEnum.PENDING.getCode().equals(orderStatus)) {
                cmsMallOrderVo.setPayStatus(OrderStatusEmnu.PAY_STATUS.NOT_PAY.getCode());
                //是否包含取消的 有值不包含
                cmsMallOrderVo.setCancelOrder(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
                cmsMallOrderVo.setRefundStatusList(refundStatusList);
            } else
                //查询待拼单的
                if (OrderStatusEmnu.CmsOrderShowStatusEnum.WAIT_GROUP.getCode().equals(orderStatus)) {
                    cmsMallOrderVo.setPayStatus(OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode());
                    //是否包含取消的 有值不包含
                    cmsMallOrderVo.setCancelOrder(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
                    cmsMallOrderVo.setOrderStatus(OrderStatusEmnu.ORDER_STATUS.WAIT_GROUP.getCode());
                    //拼单订单
                    cmsMallOrderVo.setOrderType(2);
                    cmsMallOrderVo.setRefundStatusList(refundStatusList);

                } else
                    //查询待发货的
                    if (OrderStatusEmnu.CmsOrderShowStatusEnum.WAIT_DELIVER.getCode().equals(orderStatus)) {
                        cmsMallOrderVo.setOrderStatus(OrderStatusEmnu.ORDER_STATUS.APPROVAL.getCode());
                        cmsMallOrderVo.setPayStatus(OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode());
                        cmsMallOrderVo.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode());
                        List<Integer> logisticStatusList = newArrayList();
                        logisticStatusList.add(OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode());
                        cmsMallOrderVo.setLogisticStatusList(logisticStatusList);
                        cmsMallOrderVo.setRefundStatusList(refundStatusList);
                        //是否包含取消的 有值不包含
                        cmsMallOrderVo.setCancelOrder(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
                    } else
                        //查询已经发货的
                        if (OrderStatusEmnu.CmsOrderShowStatusEnum.SHIPPED.getCode().equals(orderStatus)) {
                            cmsMallOrderVo.setRefundStatusList(refundStatusList);
                            cmsMallOrderVo.setPayStatus(OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode());
                            cmsMallOrderVo.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode());
                            List<Integer> logisticStatusList = newArrayList();
                            logisticStatusList.add(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode());
                            logisticStatusList.add(OrderStatusEmnu.LOGISTIC_STATUS.PORTION_SHIPPED.getCode());
                            cmsMallOrderVo.setLogisticStatusList(logisticStatusList);
                            cmsMallOrderVo.setCancelOrder(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
                        } else
                            // 查询已经完成的
                            if (OrderStatusEmnu.CmsOrderShowStatusEnum.TRADE_FINISHED.getCode().equals(orderStatus)) {
                                cmsMallOrderVo.setPayStatus(OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode());
                                List<Integer> logisticStatusList = newArrayList();
                                cmsMallOrderVo.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.HAVE_BEEN_SIGNED.getCode());
                                logisticStatusList.add(OrderStatusEmnu.LOGISTIC_STATUS.HAVE_BEEN_SIGNED.getCode());
                                cmsMallOrderVo.setLogisticStatusList(logisticStatusList);
                                cmsMallOrderVo.setOrderStatus(OrderStatusEmnu.ORDER_STATUS.FINISH.getCode());
                                cmsMallOrderVo.setOrderStatus2(OrderStatusEmnu.ORDER_STATUS.OVER.getCode());
                                cmsMallOrderVo.setCancelOrder(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
                                cmsMallOrderVo.setRefundStatusList(refundStatusList);
                            } else
                                //查询取消的
                                if (OrderStatusEmnu.CmsOrderShowStatusEnum.CANCELED.getCode().equals(orderStatus)) {
                                    cmsMallOrderVo.setRefundStatusList(refundStatusList);
                                    cmsMallOrderVo.setOrderStatus(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
                                }
        if (searchEnum != null) {
            if (searchEnum.equals(OrderEnums.OrderListSearchEnum.TRADE_NAME.getCode())) {
                cmsMallOrderVo.setProductName(orderNo);//产品
            } else if (searchEnum.equals(OrderEnums.OrderListSearchEnum.CONTACTER_NAME.getCode())) {
                cmsMallOrderVo.setAddresseeName(orderNo);//收货人名称
            } else if (searchEnum.equals(OrderEnums.OrderListSearchEnum.MOBILE.getCode())) {
                cmsMallOrderVo.setPhone(orderNo);//收货人手机号
            } else if (searchEnum.equals(OrderEnums.OrderListSearchEnum.WAYBILL_NUMBER.getCode())) {
                cmsMallOrderVo.setExpressNo(orderNo);//运单号码
            } else if (searchEnum.equals(OrderEnums.OrderListSearchEnum.ORDER_CODE.getCode())) {
                cmsMallOrderVo.setOrderCode(orderNo);//订单号码
            } else if (searchEnum.equals(OrderEnums.OrderListSearchEnum.BRAND.getCode())) {
                cmsMallOrderVo.setBrand(orderNo);//品牌
            } else if (searchEnum.equals(OrderEnums.OrderListSearchEnum.USER_NAME.getCode())) {
                cmsMallOrderVo.setBuyerUserName(orderNo);//用户名称
            }
        }
        cmsMallOrderVo.setShopId(shopId);
        cmsMallOrderVo.setStartTime(startDate);
        cmsMallOrderVo.setEndTime(endDate);
        // cmsMallOrderVo.setOrderCode(orderNo);
        List<Integer> payTypeList = Lists.newArrayList();
        if (payType != null) {
            cmsMallOrderVo.setPayType(payType);
            if (payType.equals(OrderEnums.PayTypeName.WECHAT.getCode())) {
                //微信
                payTypeList.add(PayEnum.PayClientShowTypeEnum.WE_CHAT.getCode());
                payTypeList.add(PayEnum.PayClientShowTypeEnum.HF_WE_CHAT.getCode());
                payTypeList.add(PayEnum.PayClientShowTypeEnum.UMF_WE_CHAT.getCode());
            } else if (payType.equals(OrderEnums.PayTypeName.BANK_CARD.getCode())) {
                payTypeList.add(PayEnum.PayClientShowTypeEnum.UNION_PAY.getCode());
                payTypeList.add(PayEnum.PayClientShowTypeEnum.UMF_CARD_PAY.getCode());
                payTypeList.add(PayEnum.PayClientShowTypeEnum.UMF_CARD_PAY.getCode());
            } else if (payType.equals(OrderEnums.PayTypeName.OFFLINE.getCode())) {
                payTypeList.add(PayEnum.PayClientShowTypeEnum.OFFLINE_PAY.getCode());
            } else {
                cmsMallOrderVo.setPayType(null);
            }
        }
        cmsMallOrderVo.setPayTypeList(payTypeList);
        return cmsMallOrderVo;
    }

    //查询详情接口
    public DataOutput<CmsMallOrderDetailsInfoVo> getOrderInfoByOrderId(Long orderId) {
        CmsMallOrderDetailsInfoVo cmsMallOrderDetailsVo = new CmsMallOrderDetailsInfoVo();
        MallOrderModel mallOrderModel = queryFactory.select(Q).from(Q).where(Q.id.eq(orderId)).fetchOne();
        MallOrderModel mallOrderModel1 = queryFactory.select(Q).from(Q).where(Q.orderCode.eq(mallOrderModel.getParentOrderCode())).fetchOne();
        if (mallOrderModel == null) {
            return base.getErrorMsg();
        }

        if (StringUtils.isNotEmpty(mallOrderModel.getOrderCode())) {
            MallOrderRefundModel mallOrderRefundModel = cmsMallOrderRefundService.getAfterSaleByOrderCode(mallOrderModel.getOrderCode());
            if (mallOrderRefundModel != null) {
                CmsMallOrderRefundVo cmsMallOrderRefundVo = new CmsMallOrderRefundVo();
                BeanUtils.copyProperties(mallOrderRefundModel, cmsMallOrderRefundVo);
                if (mallOrderRefundModel.getRefundFee() == null) {//兼容之前数据  如果没有退款金额取之前的支付金额
                    cmsMallOrderRefundVo.setRefundFee(mallOrderModel.getActualAmount());
                }
                PayStreamModel payStreamInfoRefundByOrderId = cmsPayStreamService.getPayStreamInfoRefundByOrderId(mallOrderModel1.getId());
                if (payStreamInfoRefundByOrderId != null) {
                    cmsMallOrderRefundVo.setPayTradeNo(payStreamInfoRefundByOrderId.getPayTradeNo());//退款交易流水  只有回调成功后会有
                }
                if (mallOrderRefundModel.getRefundTime() != null) {
                    cmsMallOrderRefundVo.setRefundTime(DateUtils.getDateSecondFormat(mallOrderRefundModel.getRefundTime()));
                }
                if (mallOrderRefundModel.getRefundStatus() != null) {
                    OrderStatusEmnu.ORDER_REFUND_ENUM anEnum = OrderStatusEmnu.ORDER_REFUND_ENUM.getEnum(mallOrderRefundModel.getRefundStatus());
                    if (anEnum != null) {
                        cmsMallOrderRefundVo.setRefundStatus(anEnum.getValue());
                    }
                }
                if (mallOrderRefundModel.getRefundType() != null) {
                    OrderStatusEmnu.REFUND_TYPE anEnum = OrderStatusEmnu.REFUND_TYPE.getEnum(mallOrderRefundModel.getRefundType());
                    if (anEnum != null) {
                        cmsMallOrderRefundVo.setRefundType(anEnum.getValue());
                    }
                }
                if (mallOrderRefundModel.getRefundReason() != null) {
                    OrderStatusEmnu.REFUND_REASON anEnum = OrderStatusEmnu.REFUND_REASON.getEnum(mallOrderRefundModel.getRefundReason());
                    if (anEnum != null) {
                        cmsMallOrderRefundVo.setRefundReason(anEnum.getValue());
                    }
                }
                cmsMallOrderDetailsVo.setCmsMallOrderRefundVo(cmsMallOrderRefundVo);
            }
        }

        //是否是拼单
        List<AppUserInfoDetailsVo> appUserInfoDetailsVoList = null;
        if (mallOrderModel.getOrderType().equals(OrderConstant.OrderTypeEnum.GROUP_ORDER_START.getCode()) || mallOrderModel.getOrderType().equals(OrderConstant.OrderTypeEnum.INVITED_GROUP_ORDER.getCode())) {
            appUserInfoDetailsVoList = Lists.newArrayList();
            if (mallOrderModel.getBuyerUserId() != null) {
                AppUserInfoDetailsVo appUserInfo = appUserService.getAppUserInfo(mallOrderModel.getBuyerUserId()).getData();
                if (appUserInfo != null && appUserInfo.getUserId() != null) {
                    appUserInfoDetailsVoList.add(appUserInfo);
                }
            }
            if (mallOrderModel.getShareUserId() != null) {
                AppUserInfoDetailsVo appUserInfo = appUserService.getAppUserInfo(mallOrderModel.getShareUserId()).getData();
                if (appUserInfo != null && appUserInfo.getUserId() != null) {
                    appUserInfoDetailsVoList.add(appUserInfo);
                }
            }
            cmsMallOrderDetailsVo.setAppUserInfoDetailsVoList(appUserInfoDetailsVoList);
        }

        //订单基本信息
        CmsMallOrderVo cmsMallOrderVo = new CmsMallOrderVo();
        BeanUtils.copyProperties(mallOrderModel, cmsMallOrderVo);
        cmsMallOrderVo.setFreightFee(mallOrderModel.getFreightFee());
        //店铺
        if (mallOrderModel.getShopId() != null) {
            ShopInfoDto shopInfoDto = cmsShopInfoService.getShopInfoById(mallOrderModel.getShopId());
            if (shopInfoDto != null) {
                cmsMallOrderVo.setShopName(shopInfoDto.getShopName());
            }
        }
        AppUserInfoDetailsVo appUserInfoDetailsVo = appUserService.getAppUserInfo(mallOrderModel.getBuyerUserId()).getData();
        if (appUserInfoDetailsVo != null) {
            cmsMallOrderVo.setNickName(appUserInfoDetailsVo.getNickName());//昵称
        }
        //下单时间
        if (mallOrderModel.getCreateTime() != null) {
            cmsMallOrderVo.setCreateTime(DateUtils.getDateSecondFormat(mallOrderModel.getCreateTime()));
        }
        //发货时间
        if (mallOrderModel.getShippingTime() != null) {
            cmsMallOrderVo.setShippingTime(DateUtils.getDateSecondFormat(mallOrderModel.getShippingTime()));
        }
        //优惠金额
        Long discountsAmount = 0L;
        if (mallOrderModel.getFavorableFee1() != null) {
            discountsAmount = discountsAmount + mallOrderModel.getFavorableFee1();
        }
        // 店铺用户等级优惠信息
        UserOrderGradePreferentialModel userOrderGradePreferentialModel = cmsUserOrderGradePreferentialService.findInfoByOrderId(orderId);
        if (userOrderGradePreferentialModel != null) { // 此用户为vip等级用户
            cmsMallOrderVo.setVipState(true);
            cmsMallOrderVo.setGradeName(userOrderGradePreferentialModel.getGradeName()); // 用户等级名称
            Long favorableFee3 = cmsMallOrderVo.getFavorableFee3() == null ? 0 : cmsMallOrderVo.getFavorableFee3();
            cmsMallOrderVo.setFavorableFee3ToYuan(NumberUtil.centToYuan(favorableFee3)); // 会员优惠金额
        } else {
            cmsMallOrderVo.setFavorableFee3(null); // 如果当前订单不为会员购买，将优惠金额初始化为null
            cmsMallOrderVo.setVipState(false);
        }
        /** if (mallOrderModel.getFavorableFee2() != null) {
         discountsAmount = discountsAmount + mallOrderModel.getFavorableFee2();
         }
         if (mallOrderModel.getFavorableFee3() != null) {
         discountsAmount = discountsAmount + mallOrderModel.getFavorableFee3();
         }*/
        cmsMallOrderVo.setDiscountsAmount(discountsAmount);
        //订单状态
        MallOrderDto mallOrderDto = new MallOrderDto();
        mallOrderDto.setOrderStatus(mallOrderModel.getOrderStatus());
        mallOrderDto.setPayStatus(mallOrderModel.getPayStatus());
        mallOrderDto.setLogisticStatus(mallOrderModel.getLogisticStatus());
        mallOrderDto.setOrderType(mallOrderModel.getOrderType());
        mallOrderDto.setRefundStatus(mallOrderModel.getRefundStatus());
        OrderStatusEmnu.ORDER_SHOW_STATUS orderShowStatus = buildOrderShowStatusByStatus(mallOrderDto);
        if (orderShowStatus != null) {
            cmsMallOrderVo.setOrderStatusStr(orderShowStatus.getValue());
        }
        if (mallOrderModel.getPayStatus().equals(OrderStatusEmnu.PAY_STATUS.NOT_PAY.getCode())) {
            cmsMallOrderVo.setCancelOrder(BaseEnum.YesOrNoEnum.YES.getCode());
        } else {
            cmsMallOrderVo.setCancelOrder(BaseEnum.YesOrNoEnum.NO.getCode());
        }
        List<MallOrderMoneyChangeLogModel> mallOrderMoneyChangeLogModels = cmsOrderMoneyChangeLogService.gMallOrderMoneyChangeLogByOrderId(orderId);
        if (mallOrderMoneyChangeLogModels == null) {
            mallOrderMoneyChangeLogModels = Lists.newArrayList();
        }
        if (mallOrderMoneyChangeLogModels.size() > 0) {
            cmsMallOrderVo.setCancelOrder(BaseEnum.YesOrNoEnum.YES.getCode());
        }
        /**
         * 优惠金额添加
         */
        List<MallOrderCouponsModel> mallOrderCouponsModelList = cmsMallOrderCouponsService.getMallOrderCouponsModelListByOrderId(mallOrderModel.getId());
        if (mallOrderCouponsModelList != null && mallOrderCouponsModelList.size() > 0) {
            cmsMallOrderVo.setCouponMoney(mallOrderCouponsModelList.stream().mapToLong(MallOrderCouponsModel::getActualValue).sum());
        }
        cmsMallOrderDetailsVo.setCmsMallOrderVo(cmsMallOrderVo);
        //商品信息
        List<CmsMallOrderVo> cmsMallOrderVoByParentOrderCode = null;
        List<CmsMallOrderDetailVo> mallOrderDetailDtos = Lists.newArrayList();
        if (mallOrderModel.getOrderCode() != null) {
            // cmsMallOrderVoByParentOrderCode = getCmsMallOrderVoByParentOrderCode(mallOrderModel.getOrderCode());
            //  if (cmsMallOrderVoByParentOrderCode != null && cmsMallOrderVoByParentOrderCode.size() != 0) {
            //   for (CmsMallOrderVo cmsMallOrderVo2 : cmsMallOrderVoByParentOrderCode) {
            //       if (cmsMallOrderVo2.getId() != null) {
            //查询产品详情
            List<CmsMallOrderDetailVo> mallOrderDetailDto = cmsOrderDetailService.getMallOrderDetailDto(orderId);
            mallOrderDetailDtos.addAll(mallOrderDetailDto);
        }
        // }
        //  }
        // }
        cmsMallOrderDetailsVo.setCmsMallOrderDetailVo(mallOrderDetailDtos);
        //收货人信息
        AppUserAddressVo appUserAddressVo = null;
        if (mallOrderModel.getOrderDeliveryAddressId() != null) {
            UserAddressManagementModel userAddressManagementModel = appUserAddressService.getUserAddressManagementModelById(mallOrderModel.getOrderDeliveryAddressId());
            if (userAddressManagementModel != null) {
                appUserAddressVo = new AppUserAddressVo();
                BeanUtils.copyProperties(userAddressManagementModel, appUserAddressVo);
                if (userAddressManagementModel.getSurname() != null) {
                    appUserAddressVo.setNickName(userAddressManagementModel.getNickName() + " " + userAddressManagementModel.getSurname());
                }
                StringBuffer stringBuffer = new StringBuffer();
                if (userAddressManagementModel.getAddressType() == null || !userAddressManagementModel.getAddressType()) {
                    if (userAddressManagementModel.getProvince() != null) {
                        stringBuffer.append(userAddressManagementModel.getProvince());
                    }
                    if (userAddressManagementModel.getCity() != null) {
                        stringBuffer.append(userAddressManagementModel.getCity());
                    }
                    if (userAddressManagementModel.getArea() != null) {
                        stringBuffer.append(userAddressManagementModel.getArea());
                    }
                    if (userAddressManagementModel.getAddress() != null) {
                        stringBuffer.append(userAddressManagementModel.getAddress());
                    }
                } else {
                    if (userAddressManagementModel.getAddress() != null) {
                        stringBuffer.append(userAddressManagementModel.getAddress());
                    }
                    if (userAddressManagementModel.getArea() != null) {
                        stringBuffer.append(userAddressManagementModel.getArea());
                    }
                    if (userAddressManagementModel.getCity() != null) {
                        stringBuffer.append(userAddressManagementModel.getCity());
                    }
                    if (userAddressManagementModel.getProvince() != null) {
                        stringBuffer.append(userAddressManagementModel.getProvince());
                    }
                    if (userAddressManagementModel.getCountry() != null) {
                        stringBuffer.append(" ").append(userAddressManagementModel.getCountry());
                    }


                }
                appUserAddressVo.setZipCode(userAddressManagementModel.getZipCode());
                appUserAddressVo.setAddress(stringBuffer.toString());
            }
        }
        cmsMallOrderDetailsVo.setAppUserAddressManagementVo(appUserAddressVo);
        //快递信息
        cmsMallOrderDetailsVo.setCmsOrderDeliveryVo(cmsOrderDeliveryService.getMallOrderDeliveryByOrderId(orderId));
        //支付信息
        CmsOrderPayInfoVo orderPayInfoVo = null;
        PayStreamModel payStreamModel = cmsPayStreamService.getPayStreamInfoByOrderId(mallOrderModel1.getId());
        if (payStreamModel != null) {
            //支付状态
            orderPayInfoVo = new CmsOrderPayInfoVo();
            if (payStreamModel.getPayStatus() != null) {
                PayEnum.PayStatus anEnum = PayEnum.PayStatus.getEnum(payStreamModel.getPayStatus());
                if (anEnum != null) {
                    orderPayInfoVo.setPayStatus(anEnum.getName());
                }
            }
            //支付时间
            if (payStreamModel.getPayTime() != null) {
                orderPayInfoVo.setPayTime(DateUtils.getDateSecondFormat(payStreamModel.getPayTime()));
            }
            //支付流水号
            orderPayInfoVo.setPayCode(payStreamModel.getPayTradeNo());
            //支付类型
            if (payStreamModel.getPayClientType() != null) {
                PayEnum.PayClientShowTypeEnum anEnum = PayEnum.PayClientShowTypeEnum.getEnum(payStreamModel.getPayClientType());
                if (anEnum != null) {
                    orderPayInfoVo.setPayType(anEnum.getName());
                }
            }
        }
        cmsMallOrderDetailsVo.setOrderPayInfoVo(orderPayInfoVo);

        /**
         * 身份证信息
         */
        UserCardNoDto userCardNoDto = new UserCardNoDto();
        userCardNoDto.setUserId(mallOrderModel.getBuyerUserId());
        userCardNoDto.setCardNo(mallOrderModel.getBuyerCardNo());
        List<UserCardNoModel> userCardNoList = appUserCardNoService.getUserCardNoList(userCardNoDto);
        if (userCardNoList != null && userCardNoList.size() != 0) {
            UserCardNoModel userCardNoModel = userCardNoList.get(0);
            BeanUtils.copyProperties(userCardNoModel, userCardNoDto);
        }
        cmsMallOrderDetailsVo.setUserCardNoDto(userCardNoDto);


        return base.getSuccessMsg(cmsMallOrderDetailsVo);
    }

    //查询订单状态
    public DataOutput getOrderCountByStatus(String orderNo, Integer searchEnum, String startTime, String endTime, Integer payType) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }

        PagedInput pagedInput = new PagedInput(Integer.MAX_VALUE, 1);
        PagedOutput<CmsMallOrderVo> orderList = null;
        List<CategoryVo> categoryVoList = Lists.newArrayList();
        Date startDate = null;
        if (StringUtils.isNotBlank(startTime)) {
            startDate = DateUtil.parseDate(startTime + " 00:00:00", DATE_TIME_PATTERN);
        }
        Date endDate = null;
        if (StringUtils.isNotBlank(endTime)) {
            endDate = DateUtil.parseDate(endTime + " 23:59:59", DATE_TIME_PATTERN);
        }
        CategoryVo categoryVo = null;

        //查询待发货的
        categoryVo = new CategoryVo();
        categoryVo.setKey(OrderStatusEmnu.CmsOrderShowStatusEnum.WAIT_DELIVER.getCode());

        CmsMallOrderVo cmsMallOrderVo = getCmsMallOrderVoByOrderStatus(OrderStatusEmnu.CmsOrderShowStatusEnum.WAIT_DELIVER.getCode(), userSession.getShopId(), startDate, endDate, orderNo, searchEnum, payType);
        orderList = getOrderList(pagedInput, cmsMallOrderVo, false);
        categoryVo.setValue(OrderStatusEmnu.CmsOrderShowStatusEnum.WAIT_DELIVER.getName() + " " + orderList.getTotalElements());
        categoryVoList.add(categoryVo);
        //查询已发货的
        categoryVo = new CategoryVo();
        categoryVo.setKey(OrderStatusEmnu.CmsOrderShowStatusEnum.SHIPPED.getCode());
        cmsMallOrderVo = getCmsMallOrderVoByOrderStatus(OrderStatusEmnu.CmsOrderShowStatusEnum.SHIPPED.getCode(), userSession.getShopId(), startDate, endDate, orderNo, searchEnum, payType);
        orderList = getOrderList(pagedInput, cmsMallOrderVo, false);
        categoryVo.setValue(OrderStatusEmnu.CmsOrderShowStatusEnum.SHIPPED.getName() + " " + orderList.getTotalElements());
        categoryVoList.add(categoryVo);

        //查询待付款的
        categoryVo = new CategoryVo();
        categoryVo.setKey(OrderStatusEmnu.CmsOrderShowStatusEnum.PENDING.getCode());
        cmsMallOrderVo = getCmsMallOrderVoByOrderStatus(OrderStatusEmnu.CmsOrderShowStatusEnum.PENDING.getCode(), userSession.getShopId(), startDate, endDate, orderNo, searchEnum, payType);

        orderList = getOrderList(pagedInput, cmsMallOrderVo, false);
        categoryVo.setValue(OrderStatusEmnu.CmsOrderShowStatusEnum.PENDING.getName() + " " + orderList.getTotalElements());
        categoryVoList.add(categoryVo);
        //查询拼单
        categoryVo = new CategoryVo();
        categoryVo.setKey(OrderStatusEmnu.CmsOrderShowStatusEnum.WAIT_GROUP.getCode());
        cmsMallOrderVo = getCmsMallOrderVoByOrderStatus(OrderStatusEmnu.CmsOrderShowStatusEnum.WAIT_GROUP.getCode(), userSession.getShopId(), startDate, endDate, orderNo, searchEnum, payType);
        orderList = getOrderList(pagedInput, cmsMallOrderVo, false);
        categoryVo.setValue(OrderStatusEmnu.CmsOrderShowStatusEnum.WAIT_GROUP.getName() + " " + orderList.getTotalElements());
        categoryVoList.add(categoryVo);

        //查询已完成的
        categoryVo = new CategoryVo();
        categoryVo.setKey(OrderStatusEmnu.CmsOrderShowStatusEnum.TRADE_FINISHED.getCode());
        cmsMallOrderVo = getCmsMallOrderVoByOrderStatus(OrderStatusEmnu.CmsOrderShowStatusEnum.TRADE_FINISHED.getCode(), userSession.getShopId(), startDate, endDate, orderNo, searchEnum, payType);
        orderList = getOrderList(pagedInput, cmsMallOrderVo, false);
        categoryVo.setValue(OrderStatusEmnu.CmsOrderShowStatusEnum.TRADE_FINISHED.getName() + " " + orderList.getTotalElements());
        categoryVoList.add(categoryVo);


        //查询全部的
        categoryVo = new CategoryVo();
        categoryVo.setKey(OrderStatusEmnu.CmsOrderShowStatusEnum.ALL.getCode());
        cmsMallOrderVo = getCmsMallOrderVoByOrderStatus(OrderStatusEmnu.CmsOrderShowStatusEnum.ALL.getCode(), userSession.getShopId(), startDate, endDate, orderNo, searchEnum, payType);
        orderList = getOrderList(pagedInput, cmsMallOrderVo, false);
        categoryVo.setValue(OrderStatusEmnu.CmsOrderShowStatusEnum.ALL.getName() + " " + orderList.getTotalElements());
        categoryVoList.add(categoryVo);

        //查询已经关闭的
        categoryVo = new CategoryVo();
        categoryVo.setKey(OrderStatusEmnu.CmsOrderShowStatusEnum.CANCELED.getCode());
        cmsMallOrderVo = getCmsMallOrderVoByOrderStatus(OrderStatusEmnu.CmsOrderShowStatusEnum.CANCELED.getCode(), userSession.getShopId(), startDate, endDate, orderNo, searchEnum, payType);
        orderList = getOrderList(pagedInput, cmsMallOrderVo, false);
        categoryVo.setValue(OrderStatusEmnu.CmsOrderShowStatusEnum.CANCELED.getName() + " " + orderList.getTotalElements());
        categoryVoList.add(categoryVo);
        return base.getSuccessMsg(categoryVoList);
    }


    //订单发货
    @Transactional
    public DataOutput orderDeliver(Long orderId, String expressNumber, Integer expressCode, HttpServletRequest request, String orderCode) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        Date date = new Date();
        if (orderId == null) {
            return base.getErrorMsg();
        }
        MallOrderModel mallOrderModel = queryFactory.select(Q).from(Q).where(Q.id.eq(orderId)).fetchOne();
        if (mallOrderModel == null) {
            return base.getErrorMsg();
        }
        if (!(mallOrderModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode()))) {
            if (!mallOrderModel.getPayStatus().equals(OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode())) {
                return base.getMyErrorMsg("此订单已经不能进行发货操作");
            }
        }
        if (mallOrderModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode())) {
            return base.getMyErrorMsg("订单已发货");
        }
        MallOrderDeliveryModel mallOrderDeliveryModel = new MallOrderDeliveryModel();
        mallOrderDeliveryModel.setOrderId(orderId);
        ServicesCompanyInfoModel servicesCompanyInfoModelById = cmsServicesCompanyInfoService.getServicesCompanyInfoModelById(Long.valueOf(expressCode));

        if (servicesCompanyInfoModelById == null) {
            return base.getErrorMsg("查询不到物流公司信息请重新确认");
        }
        mallOrderDeliveryModel.setDeliveryCompanyCode(servicesCompanyInfoModelById.getNameAbbr());
        mallOrderDeliveryModel.setDeliveryCompanyName(servicesCompanyInfoModelById.getCompanyName());
        if (StringUtils.isNotBlank(expressNumber)) {
            expressNumber = expressNumber.trim();
        }
        mallOrderDeliveryModel.setDeliveryNo(expressNumber);
        mallOrderDeliveryModel.setShopId(userSession.getShopId());
        mallOrderDeliveryModel.setCreateTime(date);
        mallOrderDeliveryModel.setCreateBy(Long.valueOf(userSession.getId()));
        mallOrderDeliveryModel.setOrderOrder(mallOrderModel.getOrderCode());
        mallOrderDeliveryModel.setDelete(false);
        //添加配送
        MallOrderDeliveryModel save = cmsOrderDeliveryService.save(mallOrderDeliveryModel);
        if (servicesCompanyInfoModelById.getJoinedType() != null && !servicesCompanyInfoModelById.getJoinedType().equals(1)) {
            updateOrderLogisticTaskModel(save);
        }
        List<MallOrderDetailModel> mallOrderDetailModelList = Lists.newArrayList();
        List<MallOrderDetailModel> orderDetailModelListByOrderId = cmsOrderDetailService.getOrderDetailModelListByOrderId(orderId);
        for (MallOrderDetailModel mallOrderDetailModel : orderDetailModelListByOrderId) { //哪些商品还未发货
            if (mallOrderDetailModel.getLogisticStatus() != null) {
                //商品已经发货
                if (mallOrderDetailModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode()) || mallOrderDetailModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.HAVE_BEEN_SIGNED.getCode())) {
                    continue;
                }
            }
            if (mallOrderDetailModel.getIsOutStock() != null && mallOrderDetailModel.getIsOutStock()) {
                //查询缺货数量
                ProcurementOrderDetailModel stockoutInfoByOrderDetailId = cmsProcurementOrderDetailService.getStockoutInfoByOrderDetailId(mallOrderDetailModel.getId());
                if (stockoutInfoByOrderDetailId != null) {
                    Integer qutStockQuantity = stockoutInfoByOrderDetailId.getProductQuantity() - stockoutInfoByOrderDetailId.getProcurementQuantity();//缺货数量
                    if (qutStockQuantity >= mallOrderDetailModel.getQuantity()) {
                        //商品缺货不能发货;
                        continue;
                    }
                }
            }
            mallOrderDetailModelList.add(mallOrderDetailModel);
        }

        UserAddressManagementModel userAddressManagementModelById = appUserAddressService.getUserAddressManagementModelById(mallOrderModel.getOrderDeliveryAddressId());
        // TODO 新版发货订阅
        if (kuaidi100Status) {
            if (servicesCompanyInfoModelById.getJoinedType() == null || servicesCompanyInfoModelById.getJoinedType() == 1) {
                kuaidi100CmsService.subscribeData(mallOrderDeliveryModel.getDeliveryCompanyCode(), mallOrderDeliveryModel.getDeliveryNo(), userAddressManagementModelById.getPhone());
            }
        }

       /* Map<String, String> map = Maps.newConcurrentMap();
        map.put("company", mallOrderDeliveryModel.getDeliveryCompanyCode());
        map.put("number", mallOrderDeliveryModel.getDeliveryNo());
        HttpUtils.post(logisticsPushTake, map);*/
        //然后包裹信息
        OrderDeliveryPackageInfoModel orderDeliveryPackageInfoModel = new OrderDeliveryPackageInfoModel();
        orderDeliveryPackageInfoModel.setOrderDeliveryId(save.getId());
        orderDeliveryPackageInfoModel.setPackageStatus(PackageEnum.PackageStatusEnum.SHIPPED.getCode());
        orderDeliveryPackageInfoModel.setDeliveryTime(date);
        orderDeliveryPackageInfoModel.setCreateTime(date);
        orderDeliveryPackageInfoModel.setCreateBy(userSession.getId());
        //orderDeliveryPackageInfoModel.setQuantity(quantity);
        orderDeliveryPackageInfoModel.setPackageType(PackageEnum.PackageTypeEnum.Express.getCode());
        //String packageCode = getPackageCode(date);
        // orderDeliveryPackageInfoModel.setPackageCode(packageCode);
        // orderDeliveryPackageInfoModel.setTotalMoney(mallOrderDetailModelById.getProductSalesPrice());
        orderDeliveryPackageInfoModel.setOrderId(orderId);
        orderDeliveryPackageInfoModel.setShopId(userSession.getShopId());
        orderDeliveryPackageInfoModel.setIsDelete(false);
        OrderDeliveryPackageInfoModel orderDeliveryPackageInfoModel1 = cmsOrderDeliveryPackageInfoService.save(orderDeliveryPackageInfoModel);//包裹信息

        Integer totalQuantity = 0;

        Long totalMoney = 0L;
        List<OrderDeliveryPackageModel> orderDeliveryPackageModelList = newArrayList();
        if (mallOrderDetailModelList.size() > 0) {
            for (MallOrderDetailModel mallOrderDetailModel : mallOrderDetailModelList) {
                //包裹详情
                OrderDeliveryPackageModel orderDeliveryPackageModel = new OrderDeliveryPackageModel();
                orderDeliveryPackageModel.setPackageInfoId(orderDeliveryPackageInfoModel1.getId());
                orderDeliveryPackageModel.setPackageCode(orderDeliveryPackageInfoModel1.getPackageCode());
                orderDeliveryPackageModel.setDeliveryId(orderDeliveryPackageInfoModel1.getOrderDeliveryId());
                orderDeliveryPackageModel.setPackageStatus(orderDeliveryPackageInfoModel1.getPackageStatus());
                Integer quantity = 0;
                Long money = 0L;
                if (mallOrderDetailModel.getIsOutStock() != null && mallOrderDetailModel.getIsOutStock()) {
                    //查询缺货数量
                    ProcurementOrderDetailModel stockoutInfoByOrderDetailId = cmsProcurementOrderDetailService.getStockoutInfoByOrderDetailId(mallOrderDetailModel.getId());
                    if (stockoutInfoByOrderDetailId != null) {
                        quantity = stockoutInfoByOrderDetailId.getProcurementQuantity();
                    }
                }
                money = quantity * mallOrderDetailModel.getProductSalesPrice();
                totalMoney += money;
                orderDeliveryPackageModel.setTotalMoney(money);
                orderDeliveryPackageModel.setQuantity(quantity);
                totalQuantity += quantity;
                orderDeliveryPackageModel.setIsDelete(false);
                orderDeliveryPackageModel.setOrderDetailId(mallOrderDetailModel.getId());
                orderDeliveryPackageModel.setProductId(mallOrderDetailModel.getProductId());
                orderDeliveryPackageModel.setProductSkuId(mallOrderDetailModel.getProductSkuId());
                orderDeliveryPackageModelList.add(orderDeliveryPackageModel);
                mallOrderDetailModel.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode());
                cmsOrderDetailService.save(mallOrderDetailModel);//发货
            }
        }
        orderDeliveryPackageInfoModel.setTotalMoney(totalMoney);
        orderDeliveryPackageInfoModel.setQuantity(totalQuantity);
        cmsOrderDeliveryPackageInfoService.save(orderDeliveryPackageInfoModel);
        orderDeliveryPackageService.saveList(orderDeliveryPackageModelList);//包裹信息


        mallOrderModel.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode());
        mallOrderModel.setLastUpdateBy(Long.valueOf(userSession.getId()));
        mallOrderModel.setShippingTime(date);
        mallOrderModel.setLastUpdateTime(date);
        repository.save(mallOrderModel);


        if (!StringUtils.isEmpty(mallOrderModel.getParentOrderCode())) {
            repository.updateByWhere(Q.orderCode.eq(mallOrderModel.getParentOrderCode()), it ->
                    it.set(Q.logisticStatus, OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode()).
                            set(Q.shippingTime, date).
                            set(Q.lastUpdateTime, date));
        } else {
            throw new RuntimeException("参数有误");
        }
        List<String> orderCodeList = null;
        //添加订单轨迹表
        addOrderTrack(mallOrderModel, userSession, OrderStatusEmnu.ORDER_SHOW_STATUS.SHIPPED.getKey(), OrderStatusEmnu.ORDER_SHOW_STATUS.SHIPPED.getValue(), date, OrderConstant.OrderLogType.CHILD.getCode());
        if (orderCode == null) {
            getSynchronousOrder(mallOrderModel.getParentOrderCode(), expressNumber, expressCode, orderCodeList);
        }

        if (orderCodeList == null) {
            orderCodeList = Lists.newArrayList();
            orderCodeList.add(mallOrderModel.getParentOrderCode());
        }
        Set<String> orderCodeSet = Sets.newHashSet(orderCodeList);
        for (String orderCodeS : orderCodeSet) {
            List<MallOrderModel> mallOrderModelByParentOrderCode = getMallOrderModelByParentOrderCode(orderCodeS);
            for (MallOrderModel mallOrderModel1 :
                    mallOrderModelByParentOrderCode) {
                Map<String, String> maps = Maps.newConcurrentMap();
                maps.put("orderId", mallOrderModel1.toString());
                maps.put("orderStatusStr", WeChatPushMsgEnum.DELIVER_GOODS.getTitle());
                HttpUtils.post(wxPushUrl, maps);
            }

        }

        return base.getSuccessMsg();
    }

    @Transactional
    public void getSynchronousOrder(String orderCode, String expressNumber, Integer expressCode, List<String> orderCodeList) {
        List<SynchronousOrderModel> synchronousOrderModelByOrderCodeAndSynchronousStatus = synchronousOrderService.getSynchronousOrderModelByFormerOrderCodeAndSynchronousStatus(orderCode);
        if (orderCodeList == null) {
            orderCodeList = newArrayList();
        }
        if (!orderCodeList.contains(orderCode)) {
            if (synchronousOrderModelByOrderCodeAndSynchronousStatus != null && synchronousOrderModelByOrderCodeAndSynchronousStatus.size() > 0) {
                orderCodeList.add(orderCode);
                synchronousOrder(synchronousOrderModelByOrderCodeAndSynchronousStatus, expressNumber, expressCode, orderCodeList);
            }
            //if (synchronousOrderModelByOrderCodeAndSynchronousStatus == null || synchronousOrderModelByOrderCodeAndSynchronousStatus.size() < 1) {
            synchronousOrderModelByOrderCodeAndSynchronousStatus = synchronousOrderService.getSynchronousOrderModelBySynchronousOrderCodeCodeAndSynchronousStatus(orderCode);
            if (synchronousOrderModelByOrderCodeAndSynchronousStatus != null && synchronousOrderModelByOrderCodeAndSynchronousStatus.size() > 0) {
                orderCodeList.add(orderCode);
                synchronousOrder(synchronousOrderModelByOrderCodeAndSynchronousStatus, expressNumber, expressCode, orderCodeList);
            }
        }
    }


    @Transactional
    public void getSynchronousOrderDetail(String orderCode, String expressNumber, Integer expressCode, List<String> orderCodeList, Long detailId) {
        List<SynchronousOrderModel> synchronousOrderModelByOrderCodeAndSynchronousStatus = synchronousOrderService.getSynchronousOrderModelByFormerOrderCodeAndSynchronousStatus(orderCode);
        if (orderCodeList == null) {
            orderCodeList = newArrayList();
        }
        if (!orderCodeList.contains(orderCode)) {
            if (synchronousOrderModelByOrderCodeAndSynchronousStatus != null && synchronousOrderModelByOrderCodeAndSynchronousStatus.size() > 0) {
                orderCodeList.add(orderCode);
                synchronousOrderDetail(synchronousOrderModelByOrderCodeAndSynchronousStatus, expressNumber, expressCode, orderCodeList, detailId);
            }
            //if (synchronousOrderModelByOrderCodeAndSynchronousStatus == null || synchronousOrderModelByOrderCodeAndSynchronousStatus.size() < 1) {
            synchronousOrderModelByOrderCodeAndSynchronousStatus = synchronousOrderService.getSynchronousOrderModelBySynchronousOrderCodeCodeAndSynchronousStatus(orderCode);
            if (synchronousOrderModelByOrderCodeAndSynchronousStatus != null && synchronousOrderModelByOrderCodeAndSynchronousStatus.size() > 0) {
                orderCodeList.add(orderCode);
                synchronousOrderDetail(synchronousOrderModelByOrderCodeAndSynchronousStatus, expressNumber, expressCode, orderCodeList, detailId);
            }
        }
    }

    //}
    //订单取消
    @Transactional
    public DataOutput orderCancel(Long orderId, HttpServletRequest request) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        Date date = new Date();
        if (orderId == null) {
            return base.getErrorMsg();
        }
        MallOrderModel mallOrderModel = queryFactory.select(Q).from(Q).where(Q.id.eq(orderId)).fetchOne();
        if (mallOrderModel == null) {
            return base.getErrorMsg();
        }
        if (!mallOrderModel.getPayStatus().equals(OrderStatusEmnu.PAY_STATUS.NOT_PAY.getCode())) {
            return base.getMyErrorMsg("此订单已经不能进行取消操作");
        }
        mallOrderModel.setOrderStatus(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
        mallOrderModel.setLastUpdateBy(Long.valueOf(userSession.getId()));
        mallOrderModel.setLastUpdateTime(date);
        repository.save(mallOrderModel);
        if (!StringUtils.isEmpty(mallOrderModel.getParentOrderCode())) {
            repository.updateByWhere(Q.orderCode.eq(mallOrderModel.getParentOrderCode()), it ->
                    it.set(Q.orderStatus, OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode()).
                            set(Q.shippingTime, date).
                            set(Q.lastUpdateBy, Long.valueOf(userSession.getId())).
                            set(Q.lastUpdateTime, date));
        } else {
            throw new RuntimeException("参数有误");
        }

        /**
         * 查询是否有优惠券 有的退券
         */
        refundVoucher(mallOrderModel);

        //添加订单轨迹表
        addOrderTrack(mallOrderModel, userSession, OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode(), OrderStatusEmnu.ORDER_STATUS.CANCEL.getMsg(), date, OrderConstant.OrderLogType.CHILD.getCode());
        return base.getSuccessMsg();
    }


    @Transactional
    public void synchronousOrder(List<SynchronousOrderModel> synchronousOrderModelByOrderCodeAndSynchronousStatus, String expressNumber, Integer expressCode, List<String> parentOrderCode) {
        for (SynchronousOrderModel synchronousOrderModel : synchronousOrderModelByOrderCodeAndSynchronousStatus) {
            if (synchronousOrderModel == null) {
                continue;
            }
            String synchronousOrderCode = synchronousOrderModel.getSynchronousOrderCode();
            MallOrderModel orderByOrderCode = getOrderByOrderCode(synchronousOrderCode);
            if (orderByOrderCode == null) {
                continue;
            }

            boolean decide = orderByOrderCode.getOrderCode().contains("_");
            if (!parentOrderCode.contains(orderByOrderCode.getOrderCode())) {
                if (decide) {
                    this.orderDeliver(orderByOrderCode.getId(), expressNumber, expressCode, request, orderByOrderCode.getOrderCode());
                    //parentOrderCode.add(orderByOrderCode.getOrderCode());
                    this.getSynchronousOrder(orderByOrderCode.getOrderCode(), expressNumber, expressCode, parentOrderCode);
                } else {
                    List<MallOrderModel> mallOrderModelByParentOrderCode = getMallOrderModelByParentOrderCode(orderByOrderCode.getOrderCode());
                    if (mallOrderModelByParentOrderCode != null && mallOrderModelByParentOrderCode.size() > 0) {
                        for (MallOrderModel mallOrderModel1 : mallOrderModelByParentOrderCode) {
                            this.orderDeliver(mallOrderModel1.getId(), expressNumber, expressCode, request, mallOrderModel1.getOrderCode());
                            // parentOrderCode.add(mallOrderModel1.getParentOrderCode());
                            this.getSynchronousOrder(mallOrderModel1.getParentOrderCode(), expressNumber, expressCode, parentOrderCode);
                        }
                    }
                }
            }
            String formerOrderCode = synchronousOrderModel.getFormerOrderCode();
            MallOrderModel mallOrderModel = getOrderByOrderCode(formerOrderCode);
            if (mallOrderModel == null) {
                continue;
            }
            decide = mallOrderModel.getOrderCode().contains("_");
            if (!parentOrderCode.contains(mallOrderModel.getOrderCode())) {
                if (decide) {
                    this.orderDeliver(mallOrderModel.getId(), expressNumber, expressCode, request, orderByOrderCode.getOrderCode());
                    //parentOrderCode.add(orderByOrderCode.getOrderCode());
                    this.getSynchronousOrder(mallOrderModel.getOrderCode(), expressNumber, expressCode, parentOrderCode);
                } else {
                    List<MallOrderModel> mallOrderModelByParentOrderCode = getMallOrderModelByParentOrderCode(mallOrderModel.getOrderCode());
                    if (mallOrderModelByParentOrderCode != null && mallOrderModelByParentOrderCode.size() > 0) {
                        for (MallOrderModel mallOrderModel1 : mallOrderModelByParentOrderCode) {
                            this.orderDeliver(mallOrderModel1.getId(), expressNumber, expressCode, request, mallOrderModel1.getOrderCode());
                            // parentOrderCode.add(mallOrderModel1.getParentOrderCode());
                            this.getSynchronousOrder(mallOrderModel1.getParentOrderCode(), expressNumber, expressCode, parentOrderCode);
                        }
                    }
                }
            }
            synchronousOrderModel.setSynchronousStatus(2);
            synchronousOrderService.save(synchronousOrderModel);
        }

    }

    @Transactional
    public void synchronousOrderDetail(List<SynchronousOrderModel> synchronousOrderModelByOrderCodeAndSynchronousStatus, String expressNumber, Integer expressCode, List<String> parentOrderCode, Long detailId) {
        for (SynchronousOrderModel synchronousOrderModel : synchronousOrderModelByOrderCodeAndSynchronousStatus) {
            if (synchronousOrderModel == null) {
                continue;
            }
            String synchronousOrderCode = synchronousOrderModel.getSynchronousOrderCode();
            MallOrderModel orderByOrderCode = getOrderByOrderCode(synchronousOrderCode);
            if (orderByOrderCode == null) {
                continue;
            }

            if (!parentOrderCode.contains(orderByOrderCode.getOrderCode())) {
                List<MallOrderModel> mallOrderModelByParentOrderCode = getMallOrderModelByParentOrderCode(orderByOrderCode.getOrderCode());
                setSynchronousOrderDetail(mallOrderModelByParentOrderCode, expressNumber, expressCode, parentOrderCode, detailId);
            }
            String formerOrderCode = synchronousOrderModel.getFormerOrderCode();
            MallOrderModel mallOrderModel = getOrderByOrderCode(formerOrderCode);
            if (mallOrderModel == null) {
                continue;
            }
            if (!parentOrderCode.contains(mallOrderModel.getOrderCode())) {
                List<MallOrderModel> mallOrderModelByParentOrderCode = getMallOrderModelByParentOrderCode(mallOrderModel.getOrderCode());
                setSynchronousOrderDetail(mallOrderModelByParentOrderCode, expressNumber, expressCode, parentOrderCode, detailId);
            }
            synchronousOrderService.save(synchronousOrderModel);
        }
    }

    public void setSynchronousOrderDetail(List<MallOrderModel> mallOrderModelByParentOrderCode, String expressNumber, Integer expressCode, List<String> parentOrderCode, Long detailId) {
        if (mallOrderModelByParentOrderCode != null && mallOrderModelByParentOrderCode.size() > 0) {
            for (MallOrderModel mallOrderModel1 : mallOrderModelByParentOrderCode) {
                List<MallOrderDetailModel> orderDetailModelListByOrderId = cmsOrderDetailService.getOrderDetailModelListByOrderId(mallOrderModel1.getId());
                for (MallOrderDetailModel mallOrderDetailModel : orderDetailModelListByOrderId) {
                    MallOrderDetailModel mallOrderDetailModelById = cmsOrderDetailService.getMallOrderDetailModelById(detailId);
                    ProductSkuModel productSkuDtoById = productCmsSkuService.getProductSkuDtoById(mallOrderDetailModelById.getProductSkuId());
                    String attrSpecValue = productSkuDtoById.getAttrSpecValue();
                    if (attrSpecValue == null) {
                        attrSpecValue = "";
                    }
                    String attrSpecName = productSkuDtoById.getAttrSpecName();
                    if (attrSpecName == null) {
                        attrSpecName = "";
                    }
                    String colour = productSkuDtoById.getColour();
                    if (colour == null) {
                        colour = "";
                    }
                    String productSize = productSkuDtoById.getProductSize();
                    if (productSize == null) {
                        productSize = "";
                    }
                    /**
                     * 查询待同步发货的商品
                     */
                    MallOrderDetailModel mallOrderDetailModelById1 = cmsOrderDetailService.getMallOrderDetailModelById(mallOrderDetailModel.getId());
                    ProductSkuModel productSkuDtoById1 = productCmsSkuService.getProductSkuDtoById(mallOrderDetailModelById1.getProductSkuId());
                    String attrSpecValue1 = productSkuDtoById1.getAttrSpecValue();
                    if (attrSpecValue1 == null) {
                        attrSpecValue1 = "";
                    }
                    String attrSpecName1 = productSkuDtoById1.getAttrSpecName();
                    if (attrSpecName1 == null) {
                        attrSpecName1 = "";
                    }
                    String colour1 = productSkuDtoById1.getColour();
                    if (colour1 == null) {
                        colour1 = "";
                    }
                    String productSize1 = productSkuDtoById1.getProductSize();
                    if (productSize1 == null) {
                        productSize1 = "";
                    }
                    if (attrSpecValue.equals(attrSpecValue1) &&
                            attrSpecName.equals(attrSpecName1) &&
                            colour.equals(colour1) &&
                            productSize.equals(productSize1)) {
                        partOfTheShipment(mallOrderDetailModel.getId(), expressNumber, expressCode, request, parentOrderCode);
                    }

                }
                this.getSynchronousOrderDetail(mallOrderModel1.getParentOrderCode(), expressNumber, expressCode, parentOrderCode, detailId);
            }
        }
    }


    /**
     * 添加订单轨迹信息
     *
     * @param mallOrderModel 订单信息
     * @param userSession    登陆用户
     * @param code           订单状态
     * @param msg            订单状态说明
     * @param date           操作时间
     */
    private void addOrderTrack(MallOrderModel mallOrderModel, OperationUserCmsModel userSession, Integer code, String msg, Date date, Integer orderType) {
        MallOrderLogModel mallOrderLogModel = new MallOrderLogModel();
        mallOrderLogModel.setCreateBy(String.valueOf(userSession.getId()));
        mallOrderLogModel.setCreateTime(date);
        mallOrderLogModel.setOrderType(orderType);
        mallOrderLogModel.setOrderCode(mallOrderModel.getOrderCode());
        mallOrderLogModel.setOrderId(mallOrderModel.getId());
        mallOrderLogModel.setIsDelete(false);
        mallOrderLogModel.setOperationInformation(msg);
        mallOrderLogModel.setOperationType(code);
        cmsMallOrderLogService.save(mallOrderLogModel);
    }

    /**
     * 回显枚举值
     *
     * @param mallOrderDto 订单信息
     * @return
     */
    private OrderStatusEmnu.ORDER_SHOW_STATUS buildOrderShowStatusByStatus(MallOrderDto mallOrderDto) {
        Integer orderStatus = mallOrderDto.getOrderStatus();
        Integer payStatus = mallOrderDto.getPayStatus();
        Integer logisticStatus = mallOrderDto.getLogisticStatus();
        Integer orderType = mallOrderDto.getOrderType();
        Integer refundStatus = mallOrderDto.getRefundStatus();
        if (refundStatus == null) {
            refundStatus = OrderStatusEmnu.REFUND_STATUS.STANDARD_ORDER.getCode();
        }

        if (refundStatus == OrderStatusEmnu.REFUND_STATUS.APPLYING_FOR_REFUND.getCode()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.APPLY_CANCEL;
        }
        if (refundStatus == OrderStatusEmnu.REFUND_STATUS.REFUND_REJECTED.getCode()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.REFUND_REJECTED;
        }
        if (refundStatus == OrderStatusEmnu.REFUND_STATUS.NOT_REFUND.getCode()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.NOT_REFUND;
        }
        if (refundStatus == OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND_OF.getCode()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.PORTION_REFUND_OF;
        }
        if (refundStatus == OrderStatusEmnu.REFUND_STATUS.REFUND.getCode()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.REFUND_CANCEL;
        }
        if (refundStatus == OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND.getCode()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.PORTION_REFUND;
        }
        if (refundStatus == OrderStatusEmnu.REFUND_STATUS.REFUND_ERROR.getCode()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.REFUND_FINISHED;
        }
        if (refundStatus == OrderStatusEmnu.REFUND_STATUS.PORTION_APPLYING_FOR_REFUND.getCode()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.PORTION_APPLYING_FOR_REFUND;
        }
        if (OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode() == orderStatus.intValue()) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.CANCELED;
        } else if (OrderStatusEmnu.PAY_STATUS.NOT_PAY.getCode() == payStatus.intValue() && orderStatus != OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode()) {
            //未付款(待付款)
            return OrderStatusEmnu.ORDER_SHOW_STATUS.PENDING;
        } else if (OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode() == payStatus.intValue() && orderType != null && orderType.equals(2) && OrderStatusEmnu.ORDER_STATUS.WAIT_GROUP.getCode().equals(orderStatus)) {
            // 已经付款  拼单
            return OrderStatusEmnu.ORDER_SHOW_STATUS.WAIT_GROUP;
        } else if (OrderStatusEmnu.ORDER_STATUS.APPROVAL.getCode() == orderStatus.intValue()
                && (OrderStatusEmnu.LOGISTIC_STATUS.IN_THE_STOCK.getCode() == logisticStatus.intValue())) {
            // 待发货
            return OrderStatusEmnu.ORDER_SHOW_STATUS.WAIT_DELIVER;
        } else if (OrderStatusEmnu.ORDER_STATUS.APPROVAL.getCode() == payStatus.intValue()
                && (OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode() == logisticStatus.intValue())) {
            // 已捡货
            return OrderStatusEmnu.ORDER_SHOW_STATUS.WAIT_DELIVER;
        } else if (OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode() == logisticStatus.intValue()) {
            // 已发货
            return OrderStatusEmnu.ORDER_SHOW_STATUS.SHIPPED;
        } else if (OrderStatusEmnu.ORDER_STATUS.FINISH.getCode() == orderStatus.intValue()) {
            // 交易完成
            return OrderStatusEmnu.ORDER_SHOW_STATUS.TRADE_FINISHED;

        } else if (OrderStatusEmnu.ORDER_STATUS.OVER.getCode() == orderStatus.intValue()) {
            // 交易完成
            return OrderStatusEmnu.ORDER_SHOW_STATUS.OVER;
        } else if (OrderStatusEmnu.PAY_STATUS.APPLYING_FOR_REFUND.getCode().equals(payStatus)) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.APPLY_CANCEL;
        } else if (OrderStatusEmnu.ORDER_SHOW_STATUS.REFUND_REJECTED.getKey().equals(payStatus)) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.REFUND_REJECTED;
        } else if (OrderStatusEmnu.PAY_STATUS.NOT_REFUND.getCode().equals(payStatus)) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.REFUND_CANCEL_ING;
        } else if (OrderStatusEmnu.PAY_STATUS.REFUND.getCode().equals(payStatus)) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.REFUND_CANCEL;
        } else if (OrderStatusEmnu.PAY_STATUS.REFUND_ERROR.getCode().equals(payStatus)) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.REFUND_FINISHED;
        } else if (OrderStatusEmnu.LOGISTIC_STATUS.PORTION_SHIPPED.getCode().equals(logisticStatus)) {
            return OrderStatusEmnu.ORDER_SHOW_STATUS.PARTIAL_DELIVER;
        } else {
            //订单异常
            return OrderStatusEmnu.ORDER_SHOW_STATUS.ERROR_ORDER;
        }
    }


    /**
     * 查询订单列表
     *
     * @param pagedInput     分页参数
     * @param cmsMallOrderVo 条件筛选
     */
    private PagedOutput<CmsMallOrderVo> getOrderList(PagedInput pagedInput, CmsMallOrderVo cmsMallOrderVo, Boolean isGet) {
        List<CmsMallOrderVo> cmsMallOrderVoList = newArrayList();
        String isCancel = "剔除已经取消的";

        List<Integer> orderStatuss = Lists.newArrayList();
        if (cmsMallOrderVo.getOrderStatus() != null) {
            if (cmsMallOrderVo.getOrderStatus().equals(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode())) {
                isCancel = null;
            }
            orderStatuss.add(cmsMallOrderVo.getOrderStatus());
        }
        if (cmsMallOrderVo.getOrderStatus2() != null) {
            orderStatuss.add(cmsMallOrderVo.getOrderStatus2());
        }
        PagingOrderRequestVo pagingOrderRequestVo = new PagingOrderRequestVo();
        BeanUtils.copyProperties(cmsMallOrderVo, pagingOrderRequestVo);
        if (pagedInput != null) {
            pagingOrderRequestVo.setPageNo(pagedInput.getSize() * (pagedInput.getPage() - 1));
            pagingOrderRequestVo.setPageSize(pagedInput.getSize());
        }
        pagingOrderRequestVo.setOrderStatuss(orderStatuss);

        pagingOrderRequestVo.setOrderCode(cmsMallOrderVo.getOrderCode());//订单CODE
        pagingOrderRequestVo.setBrand(cmsMallOrderVo.getBrand());//品牌
        pagingOrderRequestVo.setExpressNo(cmsMallOrderVo.getExpressNo());//运单号
        pagingOrderRequestVo.setProductName(cmsMallOrderVo.getProductName());//商品名称
        pagingOrderRequestVo.setRecipientcPhone(cmsMallOrderVo.getPhone());//  收件人手机
        pagingOrderRequestVo.setRecipientName(cmsMallOrderVo.getAddresseeName());//收件人姓名
        pagingOrderRequestVo.setNickName(cmsMallOrderVo.getBuyerUserName());//下单人昵称
        if (cmsMallOrderVo.getRefundStatusList() != null && cmsMallOrderVo.getRefundStatusList().size() > 0) {
            pagingOrderRequestVo.setRefundStatus(cmsMallOrderVo.getRefundStatusList().get(0));
        }
        List<MallOrderListDto> orderList = Lists.newArrayList();
        if (isGet) {
            orderList = orderMapper.getOrderList(pagingOrderRequestVo);
        }
        pagingOrderRequestVo.setPageNo(null);
        pagingOrderRequestVo.setPageSize(null);
        List<MallOrderListDto> orderList1 = orderMapper.getOrderList(pagingOrderRequestVo);
     /*   List<MallOrderModel> fetch = queryFactory.select(mallOrderModel1).from(mallOrderModel1)
                .leftJoin(userAddressManagementModel)
                .on(mallOrderModel1.orderDeliveryAddressId.eq(userAddressManagementModel.id))
                .where(predicateBuilder.get())
                .offset((pagedInput.getPage() - 1) * pagedInput.getSize())
                .limit(pagedInput.getSize()).orderBy(Q.createTime.desc()).fetch();*/

        List<MallOrderListDto> data = orderList;
        List<MallOrderListDto> fetch = orderList;
        Long pageTotalAmount = 0L;
        if (isGet) {
            Long totalAmount = orderList1.stream().collect(Collectors.summarizingLong(MallOrderListDto::getActualAmount)).getSum();
            for (MallOrderListDto mallOrderModel : data) {
                if (!mallOrderModel.getOrderStatus().equals(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode())) {
                    pageTotalAmount += mallOrderModel.getActualAmount();
                } else if (isCancel == null) {
                    pageTotalAmount += mallOrderModel.getActualAmount();
                }
            }
            if (fetch != null && fetch.size() != 0) {
                List<MallOrderListDto> mallOrderModelList = fetch;
                CmsMallOrderVo cmsMallOrderVo1 = null;
                for (MallOrderListDto mallOrderModel : mallOrderModelList) {
                    cmsMallOrderVo1 = new CmsMallOrderVo();
                    BeanUtils.copyProperties(mallOrderModel, cmsMallOrderVo1);
                    cmsMallOrderVo1.setTotalAmount(totalAmount);
                    cmsMallOrderVo1.setPageTotalAmount(pageTotalAmount);

                    AppUserInfoDetailsVo appUserInfoDetailsVo = appUserService.getAppUserInfo(mallOrderModel.getBuyerUserId()).getData();
                    if (appUserInfoDetailsVo != null) {
                        cmsMallOrderVo1.setBuyerUserPhone(appUserInfoDetailsVo.getPhone());//电话号码
                        cmsMallOrderVo1.setBuyerUserName(appUserInfoDetailsVo.getNickName());//昵称
                    }
                    //是否可以取消订单
                    if (mallOrderModel.getPayStatus().equals(OrderStatusEmnu.PAY_STATUS.NOT_PAY.getCode())) {
                        cmsMallOrderVo1.setCancelOrder(BaseEnum.YesOrNoEnum.YES.getCode());
                    } else {
                        cmsMallOrderVo1.setCancelOrder(BaseEnum.YesOrNoEnum.NO.getCode());
                    }
                    //是否可以发货订单
                    if (mallOrderModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode())
                            || mallOrderModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.PORTION_SHIPPED.getCode())) {
                        cmsMallOrderVo1.setDeliverOrder(BaseEnum.YesOrNoEnum.YES.getCode());
                    } else {
                        cmsMallOrderVo1.setDeliverOrder(BaseEnum.YesOrNoEnum.NO.getCode());
                    }
                    /**
                     * 到时候查询是否可以退款的状态信息
                     */

                    //创建时间
                    if (mallOrderModel.getCreateTime() != null) {
                        cmsMallOrderVo1.setCreateTime(DateUtils.getDateSecondFormat(mallOrderModel.getCreateTime()));
                    }
                    List<CmsMallOrderVo> cmsMallOrderVoByParentOrderCode = null;
                    //查询子订单
                    List<CmsMallOrderDetailVo> mallOrderDetailDtos = Lists.newArrayList();
                    // if (mallOrderModel.getOrderCode() != null) {
                    //   cmsMallOrderVoByParentOrderCode = getCmsMallOrderVoByParentOrderCode(mallOrderModel.getOrderCode());
                    // if (cmsMallOrderVoByParentOrderCode != null && cmsMallOrderVoByParentOrderCode.size() != 0) {
                    //  for (CmsMallOrderVo cmsMallOrderVo2 : cmsMallOrderVoByParentOrderCode) {
                    //    if (cmsMallOrderVo2.getId() != null) {
                    //查询产品详情
                    List<CmsMallOrderDetailVo> mallOrderDetailDto = cmsOrderDetailService.getMallOrderDetailDto(mallOrderModel.getId());
                    Integer productStockout = 0;
                    for (CmsMallOrderDetailVo cmsMallOrderDetailVo : mallOrderDetailDto) {
                        if (cmsMallOrderDetailVo.getOrderStatus() != null && cmsMallOrderDetailVo.getOrderStatus().equals("缺货")) {
                            ++productStockout;
                        }
                    }

                    String payTypeString = "";
                    MallOrderModel orderByOrderCode = getOrderByOrderCode(mallOrderModel.getParentOrderCode());
                    PayStreamModel payStreamInfoByOrderId = cmsPayStreamService.getPayStreamInfoByOrderId(orderByOrderCode.getId());
                    if (payStreamInfoByOrderId != null) {
                        if (payStreamInfoByOrderId.getPayClientType().equals(PayEnum.PayClientShowTypeEnum.WE_CHAT.getCode()) ||
                                payStreamInfoByOrderId.getPayClientType().equals(PayEnum.PayClientShowTypeEnum.HF_WE_CHAT.getCode()) ||
                                payStreamInfoByOrderId.getPayClientType().equals(PayEnum.PayClientShowTypeEnum.UMF_WE_CHAT.getCode())) {
                            payTypeString = OrderEnums.PayTypeName.WECHAT.getName();
                        } else if (payStreamInfoByOrderId.getPayClientType().equals(PayEnum.PayClientShowTypeEnum.UNION_PAY.getCode()) ||
                                payStreamInfoByOrderId.getPayClientType().equals(PayEnum.PayClientShowTypeEnum.UMF_CARD_PAY.getCode()) ||
                                payStreamInfoByOrderId.getPayClientType().equals(PayEnum.PayClientShowTypeEnum.UMF_CARD_PAY.getCode())
                        ) {
                            payTypeString = OrderEnums.PayTypeName.BANK_CARD.getName();
                        } else {
                            payTypeString = OrderEnums.PayTypeName.OFFLINE.getName();
                        }
                    }
                    cmsMallOrderVo1.setPayTypeString(payTypeString);

                    if (mallOrderDetailDto.size() <= productStockout) {
                        // 不可发货 商品全部都是缺货
                        cmsMallOrderVo1.setDeliverOrder(BaseEnum.YesOrNoEnum.NO.getCode());
                    }
                    mallOrderDetailDtos.addAll(mallOrderDetailDto);
                    if (mallOrderModel.getRefundStatus() != null) {
                        if (mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.NOT_REFUND.getCode()) ||//申请退款中
                                mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.APPLYING_FOR_REFUND.getCode()) ||//退款中
                                mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.REFUND.getCode())) {//退款成功
                            //全订单退款不能发货
                            cmsMallOrderVo1.setDeliverOrder(BaseEnum.YesOrNoEnum.NO.getCode());
                        }
                    }
                    MallOrderDto mallOrderDto = new MallOrderDto();
                    mallOrderDto.setOrderStatus(mallOrderModel.getOrderStatus());
                    mallOrderDto.setPayStatus(mallOrderModel.getPayStatus());
                    mallOrderDto.setLogisticStatus(mallOrderModel.getLogisticStatus());
                    mallOrderDto.setOrderType(mallOrderModel.getOrderType());
                    mallOrderDto.setRefundStatus(mallOrderModel.getRefundStatus());
                    OrderStatusEmnu.ORDER_SHOW_STATUS orderShowStatus = buildOrderShowStatusByStatus(mallOrderDto);
                    if (orderShowStatus != null) {
                        cmsMallOrderVo1.setOrderStatusStr(orderShowStatus.getValue());
                    }
                    if (mallOrderModel.getShopId() != null) {
                        ShopInfoDto shopInfoDto = cmsShopInfoService.getShopInfoById(mallOrderModel.getShopId());
                        if (shopInfoDto != null) {
                            cmsMallOrderVo1.setShopName(shopInfoDto.getShopName());
                        }
                    }
                    MallOrderModel orderByOrderId = getOrderByOrderId(mallOrderModel.getId());
                    if (orderByOrderId.getOrderDeliveryAddressId() != null) {
                        UserAddressManagementModel userAddressManagementModelById = appUserAddressService.getUserAddressManagementModelById(orderByOrderId.getOrderDeliveryAddressId());
                        if (userAddressManagementModelById != null) {
                            cmsMallOrderVo1.setPhone(userAddressManagementModelById.getPhone());
                            cmsMallOrderVo1.setAddresseeName(userAddressManagementModelById.getNickName());
                            if (userAddressManagementModelById.getSurname() != null) {
                                cmsMallOrderVo1.setAddresseeName(userAddressManagementModelById.getNickName() + " " + userAddressManagementModelById.getSurname());
                            }
                        }
                    }
                    // 如果用户是根据商品名搜索的吧返回的list遍历一下
                    if (StringUtils.isNotEmpty(cmsMallOrderVo.getProductName())) {
                        // 将符合名字的获取出来放到list的第一条
                        if (mallOrderDetailDto != null && mallOrderDetailDto.size() > 1) {
                            int temp = 0;
                            for (int i = 0; i < mallOrderDetailDto.size(); i++) {
                                if (mallOrderDetailDto.get(i).getProductName().contains(cmsMallOrderVo.getProductName())) {
                                    temp = i;
                                    break;
                                }
                            }
                            if (temp != 0) {
                                Collections.swap(mallOrderDetailDto, 0, temp);
                            }
                        }
                    }
                    cmsMallOrderVo1.setIsRefund(isRefund(mallOrderModel.getId()));
                    cmsMallOrderVo1.setCmsMallOrderDetailVoList(mallOrderDetailDtos);
                    String remark = redisUtil.getStr(orderByOrderId.getOrderCode());
                    if (remark == null) {
                        remark = "";
                    }
                    cmsMallOrderVo1.setSellerRemake(remark);
                    cmsMallOrderVo1.setRemake(mallOrderModel.getRemake());
                    if (mallOrderModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode()) ||
                            mallOrderModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.PORTION_SHIPPED.getCode())) {
                        if (!mallOrderModel.getOrderStatus().equals(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode())) {
                            if (mallOrderModel.getRefundStatus() == null
                                    || mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.STANDARD_ORDER.getCode())
                                    || mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.PORTION_APPLYING_FOR_REFUND.getCode())
                                    || mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.REFUND_REJECTED.getCode())
                                    || mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND_OF.getCode())
                                    || mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND.getCode())
                                    || mallOrderModel.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.REFUND_ERROR.getCode())) {
                                cmsMallOrderVo1.setUpdateLogistics(BaseEnum.YesOrNoEnum.YES.getCode());
                            }
                        }
                    }
                    /**
                     * 优惠金额添加
                     */
                    List<MallOrderCouponsModel> mallOrderCouponsModelList = cmsMallOrderCouponsService.getMallOrderCouponsModelListByOrderId(mallOrderModel.getId());
                    if (mallOrderCouponsModelList != null && mallOrderCouponsModelList.size() > 0) {
                        cmsMallOrderVo1.setCouponMoney(mallOrderCouponsModelList.stream().mapToLong(MallOrderCouponsModel::getActualValue).sum());
                    }
                    cmsMallOrderVoList.add(cmsMallOrderVo1);
                }
            }
        }
        return new PagedOutput<CmsMallOrderVo>(pagedInput, orderList1.size(), cmsMallOrderVoList);
    }

    /**
     * 查询子订单列表
     *
     * @param orderCode
     * @return
     */
    public List<CmsMallOrderVo> getCmsMallOrderVoByParentOrderCode(String orderCode) {
        List<CmsMallOrderVo> cmsMallOrderVoList = Lists.newArrayList();
        CmsMallOrderVo cmsMallOrderVo = null;
        List<MallOrderModel> mallOrderModelList = queryFactory.select(Q).from(Q).where(Q.parentOrderCode.eq(orderCode)).fetch();
        if (mallOrderModelList != null && mallOrderModelList.size() != 0) {
            for (MallOrderModel mallOrderModel : mallOrderModelList) {
                cmsMallOrderVo = new CmsMallOrderVo();
                BeanUtils.copyProperties(mallOrderModel, cmsMallOrderVo);
                cmsMallOrderVoList.add(cmsMallOrderVo);
            }
        }
        return cmsMallOrderVoList;
    }

    /**
     * 用户消费金额
     */
    public Long getUserIdOrderMoney(Long userId) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        Long money = 0L;
        Long sum = queryFactory.select(Q.actualAmount.sum()).from(Q).where(Q.parentOrderCode.notIn("").
                and(Q.payStatus.eq(OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode()).and(Q.buyerUserId.eq(userId))).and(Q.shopId.eq(userSession.getShopId()))).fetchOne();
        if (sum != null) {
            money = sum;
        }
        return money;
    }


    /**
     * 查询物流信息
     *
     * @param orderId
     * @return
     */
    public List<LogisticsInformationVo> getKuaiDiMessageList(String deliveryCompanyCode, String deliveryNo, Long orderId) {
        if (StringUtils.isBlank(deliveryCompanyCode) || StringUtils.isBlank(deliveryNo)) {
            return null;
        }
        //        先查询t_mall_order_delivery_detail 是否有物流信息，没有在调用快递100的接口  需要根据包裹号查询新的物流接口
        List<MallOrderDeliveryDetailModel> contents = cmsOrderDeliveryDetailService.getDeliveryStr(deliveryNo);
        if (contents != null && contents.size() > 0) {
            List<LogisticsInformationVo> logisticsInformationVos = newArrayList();
            List<CmsOrderLogisticsInfoVo> cmsOrderList = new ArrayList<>();
            for (MallOrderDeliveryDetailModel item : contents) {
                CmsOrderLogisticsInfoVo cmsOrderLogisticsInfoVo = new CmsOrderLogisticsInfoVo();
                cmsOrderLogisticsInfoVo.setTime(DateUtils.getDateFormat(item.getFtime(), "yyyy-MM-dd HH:mm:ss"));
                cmsOrderLogisticsInfoVo.setFtime(DateUtils.getDateFormat(item.getFtime(), "yyyy-MM-dd HH:mm:ss"));
                cmsOrderLogisticsInfoVo.setContext(item.getContext());
                cmsOrderList.add(cmsOrderLogisticsInfoVo);
            }
            LogisticsInformationVo logisticsInformationVo = new LogisticsInformationVo();
            logisticsInformationVo.setLogisticsInformationVos(cmsOrderList);
            logisticsInformationVo.setOderStateString("");
            logisticsInformationVos.add(logisticsInformationVo);
            return logisticsInformationVos;
        } else {
            String phone = "";
            MallOrderModel mallOrderModel = queryFactory.select(Q).from(Q).where(Q.id.eq(orderId)).fetchOne();
            UserAddressManagementModel userAddressManagementModel = appUserAddressService.getUserAddressManagementModelById(mallOrderModel.getOrderDeliveryAddressId());
            if (userAddressManagementModel != null && userAddressManagementModel.getPhone() != null) {
                phone = userAddressManagementModel.getPhone();
            }
            String yuantong = getKuaiDiMessage(MyStringUtils.getPingYin(deliveryCompanyCode), deliveryNo, phone);
            if (yuantong != null) {
                CmsOrderLogisticsVo cmsOrderLogisticsVo = JacksonUtils.fromJson(yuantong, CmsOrderLogisticsVo.class);
                if (cmsOrderLogisticsVo != null) {
                    List<LogisticsInformationVo> logisticsInformationVos = newArrayList();
                    LogisticsInformationVo logisticsInformationVo = new LogisticsInformationVo();
                    logisticsInformationVo.setLogisticsInformationVos(cmsOrderLogisticsVo.getData());
                    logisticsInformationVo.setOderStateString("");
                    logisticsInformationVos.add(logisticsInformationVo);
                    return logisticsInformationVos;
                    // return splitLogisticsInformation(cmsOrderLogisticsVo.getData());
                }
            }
        }
        return null;
    }

    /**
     * 描述: 拆分物流信息
     */
    private List<LogisticsInformationVo> splitLogisticsInformation(List<CmsOrderLogisticsInfoVo> list) {

        List<LogisticsInformationVo> logisticsInformationVos = Lists.newArrayList();
        if (list == null || list.size() == 0) {
            return logisticsInformationVos;
        }
        Collections.reverse(list); // 将物流信息改成正序
        // 创建多个list用来存在拆分的物流信息
        List<CmsOrderLogisticsInfoVo> procurements = new ArrayList<>(); // 采购运输中
        List<CmsOrderLogisticsInfoVo> intransits = new ArrayList<>(); // 转运中
        List<CmsOrderLogisticsInfoVo> internationalcarriages = new ArrayList<>(); // 国际运输中
        List<CmsOrderLogisticsInfoVo> customsclearances = new ArrayList<>(); // 清关中
        List<CmsOrderLogisticsInfoVo> domesticintransits = new ArrayList<>(); // 国内运输中
        List<CmsOrderLogisticsInfoVo> signfails = new ArrayList<>(); // 签收失败
        List<CmsOrderLogisticsInfoVo> havebeensigneds = new ArrayList<>(); // 已签收
        List<CmsOrderLogisticsInfoVo> canceleds = new ArrayList<>(); // 取消
        List<CmsOrderLogisticsInfoVo> tempList = new ArrayList<>();

        /*
            1.根据关键字匹配，并且每次都判断它的上一组数据是否为空，为空，优先放上一组，如果按条件都没匹配到，
            那么关键字有问题，会导致配置顺序错误，这种需要放弃保存，
         */
        for (int i = 0; i < list.size(); i++) { // 遍历获取 国际运输中指定指定的第一个位置
            Boolean flag = true;
            String content = list.get(i).getContext();
            String ftime = list.get(i).getFtime();
            if (isHave(LogisticsKeywordConstant.PROCUREMENT, content)) { // 这条信息是可能采购运输中
                flag = true;
                if (intransits.size() == 0 && internationalcarriages.size() == 0 && customsclearances.size() == 0
                        && domesticintransits.size() == 0 && signfails.size() == 0 && havebeensigneds.size() == 0
                        && canceleds.size() == 0) { // 说明这信息才开始遍历
                    procurements.add(list.get(i));
                }
            }
            if (isHave(LogisticsKeywordConstant.INTRANSIT, content)) { // 这条信息可能是转运中
                flag = false;
                if (procurements.size() == 0) { // 如果采购运输中还为空，直接放到采购运输中
                    procurements.add(list.get(i));
                } else if (procurements.size() != 0 && internationalcarriages.size() == 0 && customsclearances.size() == 0
                        && domesticintransits.size() == 0 && signfails.size() == 0 && havebeensigneds.size() == 0
                        && canceleds.size() == 0) { // 必须它后面的list要为空
                    intransits.add(list.get(i));
                }
            }
            if (isHave(LogisticsKeywordConstant.INTERNATIONALCARRIAGE, content)) { // 这条信息可能是国际运输中
                flag = false;
                if (procurements.size() == 0) { // 优先放第一组
                    procurements.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() == 0) { //
                    intransits.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() != 0 && customsclearances.size() == 0
                        && domesticintransits.size() == 0 && signfails.size() == 0 && havebeensigneds.size() == 0
                        && canceleds.size() == 0) {
                    internationalcarriages.add(list.get(i));
                }
            }
            if (isHave(LogisticsKeywordConstant.CUSTOMSCLEARANCE, content)) { // 这条信息可能是清关中
                flag = false;
                if (procurements.size() == 0) {
                    procurements.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() == 0) {
                    intransits.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() != 0 && internationalcarriages.size() == 0) {
                    internationalcarriages.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() != 0 && internationalcarriages.size() != 0
                        && domesticintransits.size() == 0 && signfails.size() == 0 && havebeensigneds.size() == 0
                        && canceleds.size() == 0) {
                    customsclearances.add(list.get(i));
                }
            }
            if (isHave(LogisticsKeywordConstant.DOMESTICINTRANSIT, content)) { // 这条可能是国内运输中
                flag = false;
                if (procurements.size() == 0) {
                    procurements.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() == 0) {
                    intransits.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() != 0 && internationalcarriages.size() == 0) {
                    internationalcarriages.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() != 0 && internationalcarriages.size() != 0
                        && customsclearances.size() == 0) {
                    customsclearances.add(list.get(i));
                } else if (procurements.size() != 0 && intransits.size() != 0 && internationalcarriages.size() != 0 && customsclearances.size() != 0
                        && signfails.size() == 0 && havebeensigneds.size() == 0 && canceleds.size() == 0) {
                    domesticintransits.add(list.get(i));
                }
            }
            if (isHave(LogisticsKeywordConstant.SIGNFAIL, content)) { // 这条信息可能是签收失败
                flag = false;
                signfails.add(list.get(i)); // 签收失败，只能放在签收失败
            }
            if (isHave(LogisticsKeywordConstant.HAVEBEENSIGNED, content)) { // 这条信息可能是已签收
                flag = false;
                havebeensigneds.add(list.get(i)); // 签收成功的只能放到签收成功里
            }
            if (isHave(LogisticsKeywordConstant.CANCELED, content)) { // 这条信息可能是取消
                flag = false;
                canceleds.add(list.get(i)); // 取消的只能放到取消里
            }

        }
        /*
            3.判断临时list是否为空，如果为空，获取这条信息的时间，
             并且需要遍历每个list中的第一条和最后一条信息，判断这个信息应该放到，放到哪个组中
        */
        if (tempList != null && tempList.size() != 0) {
            // 有未匹配到的数据
            for (CmsOrderLogisticsInfoVo kuaiDi100DetailVo : tempList) {
                // 获取这条信息的创建时间
                String ftime1 = kuaiDi100DetailVo.getFtime(); // 物流信息创建时间
                // 先从第一组中开始获取数据
                if (procurements.size() == 0) {
                    procurements.add(kuaiDi100DetailVo);
                    continue;
                } else if (procurements.size() != 0) { // 对这条数据
                    CmsOrderLogisticsInfoVo kuaiDi100 = procurements.get(procurements.size() - 1); // 获取最后一条数据
                    int i1 = DateUtils.compareDate(ftime1, kuaiDi100.getFtime());//比较两个时间的最大
                    if (i1 < 0) { // 如果小于0，则需要开始遍历这个list, 并插入到该list
                        compareAndAdd(kuaiDi100DetailVo, procurements);
                        continue;
                    } else if (intransits.size() == 0) { // 如果等于0，直接插入到上一组数据的最后一条，下同理
                        procurements.add(kuaiDi100DetailVo);
                        continue;
                    } else if (intransits.size() != 0) { // 转运中
                        CmsOrderLogisticsInfoVo kuaiDi100DetailVo1 = intransits.get(intransits.size() - 1);
                        int i2 = DateUtils.compareDate(ftime1, kuaiDi100DetailVo1.getFtime());
                        if (i2 < 0) { // 如果小于0， 则遍历这个list，并插入到该list
                            compareAndAdd(kuaiDi100DetailVo, intransits);
                            continue;
                        } else if (internationalcarriages.size() == 0) {
                            intransits.add(kuaiDi100DetailVo);
                            continue;
                        } else if (internationalcarriages.size() != 0) { // 国际运输中
                            CmsOrderLogisticsInfoVo kuaiDi100DetailVo2 = internationalcarriages.get(internationalcarriages.size() - 1);
                            int i3 = DateUtils.compareDate(ftime1, kuaiDi100DetailVo2.getFtime());
                            if (i3 < 0) { // 如果小于0， 则遍历这个list，并插入到该list， 下同理
                                compareAndAdd(kuaiDi100DetailVo, internationalcarriages);
                                continue;
                            } else if (customsclearances.size() == 0) {
                                internationalcarriages.add(kuaiDi100DetailVo);
                                continue;
                            } else if (customsclearances.size() != 0) { // 清关中
                                CmsOrderLogisticsInfoVo kuaiDi100DetailVo3 = customsclearances.get(customsclearances.size() - 1);
                                int i4 = DateUtils.compareDate(ftime1, kuaiDi100DetailVo3.getFtime());
                                if (i4 < 0) {
                                    compareAndAdd(kuaiDi100DetailVo, customsclearances);
                                    continue;
                                } else if (domesticintransits.size() == 0) {
                                    customsclearances.add(kuaiDi100DetailVo);
                                    continue;
                                } else if (domesticintransits.size() != 0) { // 国内运输中
                                    CmsOrderLogisticsInfoVo kuaiDi100DetailVo4 = domesticintransits.get(domesticintransits.size() - 1);
                                    int i = DateUtils.compareDate(ftime1, kuaiDi100DetailVo4.getFtime());
                                    if (i < 0) {
                                        compareAndAdd(kuaiDi100DetailVo, domesticintransits);
                                        continue;
                                    } else if (signfails.size() == 0) {
                                        domesticintransits.add(kuaiDi100DetailVo);
                                        continue;
                                    } else if (signfails.size() != 0) { // 签收失败 和已签收并列
                                        CmsOrderLogisticsInfoVo kuaiDi100DetailVo5 = signfails.get(signfails.size() - 1);
                                        int i5 = DateUtils.compareDate(ftime1, kuaiDi100DetailVo5.getFtime());
                                        if (i5 < 0) {
                                            compareAndAdd(kuaiDi100DetailVo, signfails);
                                            continue;
                                        }
                                    } else if (havebeensigneds.size() == 0) { // 已签收
                                        domesticintransits.add(kuaiDi100DetailVo);
                                        continue;
                                    } else if (havebeensigneds.size() != 0) {
                                        CmsOrderLogisticsInfoVo kuaiDi100DetailVo5 = havebeensigneds.get(havebeensigneds.size() - 1);
                                        int i5 = DateUtils.compareDate(ftime1, kuaiDi100DetailVo5.getFtime());
                                        if (i5 < 0) {
                                            compareAndAdd(kuaiDi100DetailVo, havebeensigneds);
                                            continue;
                                        }
                                    } else { // 取消件
                                        canceleds.add(kuaiDi100DetailVo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // 4.将不为空的list，全部都倒序一下
        // 5.将每组list存放到KuaiDi100Vo

        if (procurements.size() != 0) {
            Collections.reverse(procurements); // 倒序
            // 5.1 采购运输中信息
            LogisticsInformationVo logisticsInformationVo = resultTrim(procurements, OrderStatusEmnu.EXPRESSAGE_STATUS.COLLECTED);
            logisticsInformationVos.add(logisticsInformationVo);
        }
        if (intransits.size() != 0) {
            Collections.reverse(intransits);
            // 5.2 转运中
            LogisticsInformationVo logisticsInformationVo1 = resultTrim(intransits, OrderStatusEmnu.EXPRESSAGE_STATUS.IN_TRANSIT);
            logisticsInformationVos.add(logisticsInformationVo1);
        }
        if (internationalcarriages.size() != 0) {
            Collections.reverse(internationalcarriages);
            // 5.3 国际运输中
            LogisticsInformationVo logisticsInformationVo2 = resultTrim(internationalcarriages, OrderStatusEmnu.EXPRESSAGE_STATUS.IN_INTERNATIONAL_TRANSPOR);
            logisticsInformationVos.add(logisticsInformationVo2);
        }
        if (customsclearances.size() != 0) {
            Collections.reverse(customsclearances);
            // 5.4 清关中
            LogisticsInformationVo logisticsInformationVo3 = resultTrim(customsclearances, OrderStatusEmnu.EXPRESSAGE_STATUS.CUSTOMS_CLEARANCE);
            logisticsInformationVos.add(logisticsInformationVo3);
        }
        if (domesticintransits.size() != 0) {
            Collections.reverse(domesticintransits);
            // 5.5 国内运输中
            LogisticsInformationVo logisticsInformationVo4 = resultTrim(domesticintransits, OrderStatusEmnu.EXPRESSAGE_STATUS.IN_DOMESTIC_TRANSPORT);
            logisticsInformationVos.add(logisticsInformationVo4);
        }
        if (signfails.size() != 0) {
            Collections.reverse(signfails);
            // 5.6 签收失败
            LogisticsInformationVo logisticsInformationVo5 = resultTrim(signfails, OrderStatusEmnu.EXPRESSAGE_STATUS.FAILURE_TO_SIGN);
            logisticsInformationVos.add(logisticsInformationVo5);
        }
        if (havebeensigneds.size() != 0) {
            Collections.reverse(havebeensigneds);
            // 5.7 已签收
            LogisticsInformationVo logisticsInformationVo = resultTrim(havebeensigneds, OrderStatusEmnu.EXPRESSAGE_STATUS.HAVE_BEEN_SIGNED);
            logisticsInformationVos.add(logisticsInformationVo);
        }
        if (canceleds.size() != 0) {
            Collections.reverse(canceleds);
            LogisticsInformationVo logisticsInformationVo = resultTrim(canceleds, OrderStatusEmnu.EXPRESSAGE_STATUS.CANCEL);
            logisticsInformationVos.add(logisticsInformationVo);
        }
        // 最后把整个logisticsInformationVos倒序一下
        Collections.reverse(logisticsInformationVos);
        return logisticsInformationVos;
    }

    private LogisticsInformationVo resultTrim(List<CmsOrderLogisticsInfoVo> list, OrderStatusEmnu.EXPRESSAGE_STATUS msg) {
        LogisticsInformationVo logisticsInformationVo = new LogisticsInformationVo();
        logisticsInformationVo.setOderStateString(msg.getMsg());
        logisticsInformationVo.setOrderState(msg.getCode());
        logisticsInformationVo.setLogisticsInformationVos(list);
        return logisticsInformationVo;
    }


    /**
     * 描述: 从快递100实时获取订单信息
     *
     * @param companyCode 快递公司编号(必填) 例：yuantong
     * @param deliveryNo  快递单号(必填)
     * @param phone       手机号(顺丰快递时必填)
     */
    public String getKuaiDiMessage(String companyCode, String deliveryNo, String phone) {
        if (StringUtils.isBlank(companyCode) || StringUtils.isBlank(deliveryNo)) {
            return null;
        }
        String result = null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("com", companyCode);
        jsonObject.put("num", deliveryNo);
        jsonObject.put("phone", phone);
        String param = jsonObject.toJSONString();
        try {
            String sign = MD5EncryptionUtils.getMd5(param + key + customer).toUpperCase();
            Map<String, String> params = new HashMap<>();
            params.put("param", param);
            params.put("sign", sign);
            params.put("customer", customer);
            result = HttpUtil.post(url, params);
            System.out.println(result);
        } catch (Exception e) {
            logger.error("获取物流信息异常", e);
        }
        return result;
    }

    private boolean isHave(String[] param, String s) {
        /*此方法有两个参数，第一个是要查找的字符串数组，第二个是要查找的字符或字符串*/
        int i = 0;
        while (i < param.length) {
            Pattern pattern = Pattern.compile(param[i]);
            Matcher matcher = pattern.matcher(s);
            boolean rs = matcher.find();
            if (rs) {
                return true;
            }
            i++;
        }
        return false;
    }

    @Transactional
    public MallOrderModel save(MallOrderModel mallOrderModel) {
        return repository.save(mallOrderModel);
    }

    public Long getOrderNumberByUser(Long userId) {
        return queryFactory.select(Q).from(Q).where(Q.buyerUserId.eq(userId)).fetchCount();
    }

    public MallOrderModel getOrderByOrderId(Long orderId) {
        return queryFactory.select(Q).from(Q).where(Q.id.eq(orderId)).fetchOne();
    }

    /**
     * 描述: 按时间将数据插入到list中，并且将他们正序输出
     *
     * @param
     * @return
     * @auther: Kien
     */
    private void compareAndAdd(CmsOrderLogisticsInfoVo kuaiDi100DetailVo, List<CmsOrderLogisticsInfoVo> list) {
        list.add(kuaiDi100DetailVo);
        Collections.sort(list, new Comparator<CmsOrderLogisticsInfoVo>() {
            @Override
            public int compare(CmsOrderLogisticsInfoVo o1, CmsOrderLogisticsInfoVo o2) {
                int i = DateUtils.compareDate(o1.getFtime(), o2.getFtime());
                if (i > 0) {
                    return 1;
                } else if (i < 0) {
                    return -1;
                }
                return 0;
            }
        });
    }

    /**
     * 根据订单编号查询信息
     *
     * @param orderNo
     * @return
     */
    public List<MallOrderModel> findOrderInfoByOrderNo(String orderNo) {
        List<MallOrderModel> list = repository.findAll(Q.orderCode.eq(orderNo));
        return list;
    }

    @Autowired
    private CmsMallOrderRefundDetailService cmsMallOrderRefundDetailService;

    /**
     * 售后退款
     *
     * @param mallOrderRefundModel
     */
    @Transactional
    public PayStreamDto updateOrderAfterSaleRefund(MallOrderRefundModel mallOrderRefundModel) {

        PayStreamModel payStreamModel = null;
        PayStreamDto payStreamDto = null;
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }
        MallOrderModel mallOrderModel = getOrderByOrderId(mallOrderRefundModel.getOrderId());
        if (mallOrderModel != null) {
            if (mallOrderRefundModel.getRefundFee() > mallOrderModel.getActualAmount()) {
                throw new YiTaoCmsRuntimeException("退款失败,退款金额不能超过支付金额");
            }
            //  mallOrderModel.setOrderStatus(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
            if (mallOrderRefundModel.getRefundType().equals(OrderStatusEmnu.REFUND_TYPE.STOCK_OUT_REFUND.getKey())) {
                mallOrderModel.setRefundStatus(OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND_OF.getCode());

                List<MallOrderRefundDetailModel> mallOrderRefundDetailModelListByRefundId = cmsMallOrderRefundDetailService.getMallOrderRefundDetailModelListByRefundId(mallOrderRefundModel.getId());
                if (mallOrderRefundDetailModelListByRefundId != null && mallOrderRefundDetailModelListByRefundId.size() > 0) {
                    for (MallOrderRefundDetailModel mallOrderRefundDetailModel : mallOrderRefundDetailModelListByRefundId) {
                        MallOrderDetailModel orderDetailModelListById = cmsOrderDetailService.getMallOrderDetailModelById(mallOrderRefundDetailModel.getOrderDetailId());
                        if (orderDetailModelListById != null) {
                            if (orderDetailModelListById.getQuantity() == null) {
                                continue;
                            }
                            if (orderDetailModelListById.getQuantity() == mallOrderRefundDetailModel.getQuantity()) {
                                orderDetailModelListById.setRefundStatus(OrderStatusEmnu.REFUND_STATUS.NOT_REFUND.getCode());
                            } else {
                                orderDetailModelListById.setRefundStatus(mallOrderModel.getRefundStatus());
                            }
                        }
                        cmsOrderDetailService.save(orderDetailModelListById);
                    }
                }
            } else {
                mallOrderModel.setRefundStatus(OrderStatusEmnu.REFUND_STATUS.NOT_REFUND.getCode());
                /**
                 * 查询是否有优惠券 有的退券
                 */
                refundVoucher(mallOrderModel);
            }
            mallOrderModel.setLastUpdateTime(mallOrderRefundModel.getLastUpdateTime());
            mallOrderModel.setLastUpdateBy(mallOrderRefundModel.getLastUpdateBy());
            // addOrderTrack(mallOrderModel, userSession, OrderStatusEmnu.ORDER_SHOW_STATUS.CANCELED.getKey(), OrderStatusEmnu.ORDER_SHOW_STATUS.CANCELED.getValue(), mallOrderRefundModel.getLastUpdateTime(), OrderConstant.OrderLogType.PARENT.getCode());
            repository.save(mallOrderModel);
            MallOrderModel mallOrderModel1 = getOrderByOrderCode(mallOrderModel.getParentOrderCode());
            if (mallOrderModel1 != null) {
                mallOrderModel1.setRefundStatus(mallOrderModel.getRefundStatus());
                mallOrderModel1.setLastUpdateTime(mallOrderRefundModel.getLastUpdateTime());
                mallOrderModel1.setLastUpdateBy(mallOrderRefundModel.getLastUpdateBy());
                repository.save(mallOrderModel1);
            }

            payStreamModel = cmsPayStreamService.getPayStreamInfoByOrderId(mallOrderModel1.getId());
            //  payStreamModel.setOrderId(mallOrderModel.getId());
            payStreamDto = new PayStreamDto();
            BeanUtils.copyProperties(payStreamModel, payStreamDto);
            payStreamDto.setOrderId(mallOrderModel.getId());
        }
        return payStreamDto;
    }

    /**
     * 退券接口
     */
    @Transactional
    public void refundVoucher(MallOrderModel mallOrderModel) {
        List<MallOrderCouponsModel> mallOrderCouponsModelListByOrderId = cmsMallOrderCouponsService.getMallOrderCouponsModelListByOrderId(mallOrderModel.getId());
        if (mallOrderCouponsModelListByOrderId != null || mallOrderCouponsModelListByOrderId.size() > 0) {
            for (MallOrderCouponsModel mallOrderCouponsModel : mallOrderCouponsModelListByOrderId) {
                CashCouponsInfoDto cashCouponsInfoByCode = cashCouponsService.getCashCouponsInfoByCode(mallOrderCouponsModel.getCouponsCode());
                if (cashCouponsInfoByCode != null) {
                    cashCouponsInfoByCode.setDeleteStatus(true);
                    cashCouponsService.updateCashCouponsInfoByBean(cashCouponsInfoByCode);
                }
                //添加优惠券
                cashCouponsService.addCashCouponsInfo(mallOrderCouponsModel.getShopId(), mallOrderCouponsModel.getCouponsId(), mallOrderCouponsModel.getUserId(), mallOrderModel.getBuyerUserName());
            }
        }
    }

    /**
     * 更具订单code查询订单
     */
    public MallOrderModel getOrderByOrderCode(String orderCode) {
        return queryFactory.select(Q).from(Q).where(Q.orderCode.eq(orderCode)).fetchOne();
    }

    /**
     * 标记缺货
     *
     * @param orderDetailId
     * @param quantity
     * @return
     */
    public DataOutput stockoutTab(Long orderDetailId, Integer quantity) {
        Date date = new Date();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }
        if (orderDetailId == null || quantity == null) {
            return base.getErrorMsg();
        }
        if (quantity < 1) {
            return base.getErrorMsg("缺货数量不能小于 1 ");
        }
        MallOrderDetailModel mallOrderDetailModelById = cmsOrderDetailService.getMallOrderDetailModelById(orderDetailId);
        if (mallOrderDetailModelById == null) {
            return base.getErrorMsg();
        }
        if (mallOrderDetailModelById.getQuantity() < quantity) {
            return base.getErrorMsg("缺货数量不能大于实际购买数量");
        }
        ProcurementOrderDetailModel stockoutInfoByOrderDetailId = cmsProcurementOrderDetailService.getStockoutInfoByOrderDetailId(mallOrderDetailModelById.getId());
        if (stockoutInfoByOrderDetailId != null) {
            return base.getErrorMsg("当前商品已经标记缺货不可重复标记");
        }
        MallOrderModel orderByOrderId = getOrderByOrderId(mallOrderDetailModelById.getOrderId());
        if (orderByOrderId == null) {
            return base.getErrorMsg("订单不存在");
        }
        ProcurementOrderDetailModel procurementOrderDetailModel = new ProcurementOrderDetailModel();
        procurementOrderDetailModel.setIsDelete(false);
        procurementOrderDetailModel.setCreateBy(userSession.getId());
        procurementOrderDetailModel.setCreateTime(date);
        procurementOrderDetailModel.setEndTime(date);
        procurementOrderDetailModel.setShopId(userSession.getShopId());
        procurementOrderDetailModel.setFatherOrderCode(orderByOrderId.getParentOrderCode());
        procurementOrderDetailModel.setOrderDetailId(mallOrderDetailModelById.getId());
        procurementOrderDetailModel.setSonOrderCode(orderByOrderId.getOrderCode());
        procurementOrderDetailModel.setProductQuantity(mallOrderDetailModelById.getQuantity());
        procurementOrderDetailModel.setSonOrderId(orderByOrderId.getId());
        procurementOrderDetailModel.setProcurementQuantity(mallOrderDetailModelById.getQuantity() - quantity);//计算实际购买数量
        procurementOrderDetailModel.setProcurementStatus(4);//缺货
        cmsProcurementOrderDetailService.save(procurementOrderDetailModel);
        mallOrderDetailModelById.setIsOutStock(true);//商品缺货
        cmsOrderDetailService.save(mallOrderDetailModelById);
        return base.getSuccessMsg();
    }

    /**
     * 商品发货
     *
     * @param orderDetailId
     * @param expressNumber
     * @param expressCode
     * @param request
     * @return
     */
    @Transactional
    public DataOutput partOfTheShipment(Long orderDetailId, String expressNumber, Integer expressCode, HttpServletRequest request, List<String> orderCodeList) {

        Date date = new Date();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }
        MallOrderDetailModel mallOrderDetailModelById = cmsOrderDetailService.getMallOrderDetailModelById(orderDetailId);
        if (mallOrderDetailModelById == null) {
            return base.getErrorMsg("查询不到商品信息");
        }
        if (mallOrderDetailModelById.getLogisticStatus() != null && mallOrderDetailModelById.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode())
                && mallOrderDetailModelById.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.HAVE_BEEN_SIGNED.getCode())) {
            return base.getErrorMsg("当前商品已发货");
        }
        MallOrderModel orderByOrderId = this.getOrderByOrderId(mallOrderDetailModelById.getOrderId());
        if (orderByOrderId == null) {
            return base.getErrorMsg("查询不到订单信息");
        }
        if (orderByOrderId.getPayStatus() == null || orderByOrderId.getPayStatus().equals(OrderStatusEmnu.PAY_STATUS.NOT_PAY.getCode())) {
            return base.getErrorMsg("订单未支付不能发货");
        }

        ServicesCompanyInfoModel servicesCompanyInfoModelById = cmsServicesCompanyInfoService.getServicesCompanyInfoModelById(Long.valueOf(expressCode));

        Boolean isOutStock = mallOrderDetailModelById.getIsOutStock();
        if (isOutStock != null && isOutStock) {
            ProcurementOrderDetailModel stockoutInfoByOrderDetailId = cmsProcurementOrderDetailService.getStockoutInfoByOrderDetailId(mallOrderDetailModelById.getId());
            if (stockoutInfoByOrderDetailId != null) {
                Integer qutStockQuantity = stockoutInfoByOrderDetailId.getProductQuantity() - stockoutInfoByOrderDetailId.getProcurementQuantity();//缺货数量
                if (qutStockQuantity >= mallOrderDetailModelById.getQuantity()) {
                    return base.getErrorMsg("商品缺货不能发货");
                }
            }
        }
        if (servicesCompanyInfoModelById == null) {
            return base.getErrorMsg("查询不到物流公司信息请重新确认");
        }
        //先添加一条物流信息
        MallOrderDeliveryModel mallOrderDeliveryModel = new MallOrderDeliveryModel();
        mallOrderDeliveryModel.setCreateBy(userSession.getId());
        mallOrderDeliveryModel.setDeliveryNo(expressNumber);
        mallOrderDeliveryModel.setCreateTime(date);
        mallOrderDeliveryModel.setDelete(false);
        mallOrderDeliveryModel.setShopId(userSession.getShopId());
        mallOrderDeliveryModel.setOrderId(orderByOrderId.getId());
        mallOrderDeliveryModel.setDeliveryCompanyName(servicesCompanyInfoModelById.getCompanyName());
        mallOrderDeliveryModel.setDeliveryCompanyCode(servicesCompanyInfoModelById.getNameAbbr());
        MallOrderDeliveryModel mallOrderDeliveryModel1 = cmsOrderDeliveryService.save(mallOrderDeliveryModel);
        if (servicesCompanyInfoModelById.getJoinedType() != null && !servicesCompanyInfoModelById.getJoinedType().equals(1)) {
            updateOrderLogisticTaskModel(mallOrderDeliveryModel1);
        }

        UserAddressManagementModel userAddressManagementModelById = appUserAddressService.getUserAddressManagementModelById(orderByOrderId.getOrderDeliveryAddressId());

        // TODO 快递100订阅
        if (kuaidi100Status) {
            if (servicesCompanyInfoModelById.getJoinedType() == null || servicesCompanyInfoModelById.getJoinedType() == 1) {
                kuaidi100CmsService.subscribeData(mallOrderDeliveryModel.getDeliveryCompanyCode(), mallOrderDeliveryModel.getDeliveryNo(), userAddressManagementModelById.getPhone());
            }
        }
        //http 订阅
        /*Map<String, String> map = Maps.newConcurrentMap();
        map.put("company", mallOrderDeliveryModel.getDeliveryCompanyCode());
        map.put("number", mallOrderDeliveryModel.getDeliveryNo());
        HttpUtils.post(logisticsPushTake, map);*/


        //然后包裹信息
        OrderDeliveryPackageInfoModel orderDeliveryPackageInfoModel = new OrderDeliveryPackageInfoModel();
        orderDeliveryPackageInfoModel.setOrderDeliveryId(mallOrderDeliveryModel1.getId());
        orderDeliveryPackageInfoModel.setPackageStatus(PackageEnum.PackageStatusEnum.SHIPPED.getCode());
        orderDeliveryPackageInfoModel.setDeliveryTime(date);
        orderDeliveryPackageInfoModel.setCreateTime(date);
        orderDeliveryPackageInfoModel.setCreateBy(userSession.getId());
        Integer quantity = mallOrderDetailModelById.getQuantity();
        if (mallOrderDetailModelById.getIsOutStock() != null && mallOrderDetailModelById.getIsOutStock()) {
            //查询缺货数量
            ProcurementOrderDetailModel stockoutInfoByOrderDetailId = cmsProcurementOrderDetailService.getStockoutInfoByOrderDetailId(mallOrderDetailModelById.getId());
            if (stockoutInfoByOrderDetailId != null) {
                quantity = stockoutInfoByOrderDetailId.getProcurementQuantity();
            }
        }
        orderDeliveryPackageInfoModel.setQuantity(quantity);
        orderDeliveryPackageInfoModel.setPackageType(PackageEnum.PackageTypeEnum.Express.getCode());
        String packageCode = getPackageCode(date);
        orderDeliveryPackageInfoModel.setPackageCode(packageCode);
        orderDeliveryPackageInfoModel.setTotalMoney(mallOrderDetailModelById.getProductSalesPrice());
        orderDeliveryPackageInfoModel.setOrderId(mallOrderDetailModelById.getOrderId());
        orderDeliveryPackageInfoModel.setShopId(userSession.getShopId());
        orderDeliveryPackageInfoModel.setIsDelete(false);
        OrderDeliveryPackageInfoModel orderDeliveryPackageInfoModel1 = cmsOrderDeliveryPackageInfoService.save(orderDeliveryPackageInfoModel);//包裹信息

        //包裹详情
        OrderDeliveryPackageModel orderDeliveryPackageModel = new OrderDeliveryPackageModel();
        orderDeliveryPackageModel.setOrderDetailId(mallOrderDetailModelById.getId());
        orderDeliveryPackageModel.setPackageInfoId(orderDeliveryPackageInfoModel1.getId());
        orderDeliveryPackageModel.setPackageCode(orderDeliveryPackageInfoModel1.getPackageCode());
        orderDeliveryPackageModel.setTotalMoney(orderDeliveryPackageInfoModel1.getTotalMoney());
        orderDeliveryPackageModel.setDeliveryId(orderDeliveryPackageInfoModel1.getOrderDeliveryId());
        orderDeliveryPackageModel.setPackageStatus(orderDeliveryPackageInfoModel1.getPackageStatus());
        orderDeliveryPackageModel.setProductId(mallOrderDetailModelById.getProductId());
        orderDeliveryPackageModel.setProductSkuId(mallOrderDetailModelById.getProductSkuId());
        orderDeliveryPackageModel.setIsDelete(false);
        orderDeliveryPackageService.save(orderDeliveryPackageModel);//添加包裹详情


        Boolean decide = true; //用来判断商品是否全部发货
        //修改商品信息
        mallOrderDetailModelById.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode());
        mallOrderDetailModelById.setLastUpdateTime(date);
        mallOrderDetailModelById.setLastUpdateBy(userSession.getId());
        cmsOrderDetailService.save(mallOrderDetailModelById);
        //修改子订单状态
        List<MallOrderDetailModel> orderDetailIdList = newArrayList();
        orderDetailIdList.add(mallOrderDetailModelById);
        List<MallOrderDetailModel> mallOrderDetailModelList = cmsOrderDetailService.getOrderDetailModelListNotIn(orderByOrderId.getId(), orderDetailIdList);
        for (MallOrderDetailModel mallOrderDetailModel : mallOrderDetailModelList) {
            if (mallOrderDetailModel.getIsOutStock() != null && mallOrderDetailModel.getIsOutStock()) {
                continue;//标记缺货的直接掠过
            }
            if (mallOrderDetailModel.getLogisticStatus() == null ||//等于null
                    mallOrderDetailModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.IN_THE_STOCK.getCode()) ||//备货中
                    mallOrderDetailModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode()) ||//待发货
                    mallOrderDetailModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.PORTION_SHIPPED.getCode())) {//部分发货
                decide = false;//订单没完全发货
                break;
            }
        }


        if (orderCodeList == null) {
            orderCodeList = Lists.newArrayList();
            // orderCodeList.add(orderByOrderId.getParentOrderCode());
        }
        if (decide) {
            orderByOrderId.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode());//全部发货
            //添加订单轨迹表
            addOrderTrack(orderByOrderId, userSession, OrderStatusEmnu.ORDER_SHOW_STATUS.SHIPPED.getKey(), OrderStatusEmnu.ORDER_SHOW_STATUS.SHIPPED.getValue(), date, OrderConstant.OrderLogType.CHILD.getCode());
            //订单推送
            Map<String, String> maps = Maps.newConcurrentMap();
            maps.put("orderId", orderByOrderId.getId().toString());
            maps.put("orderStatusStr", WeChatPushMsgEnum.DELIVER_GOODS.getMessage());
            HttpUtils.post(wxPushUrl, maps);
            getSynchronousOrder(orderByOrderId.getParentOrderCode(), expressNumber, expressCode, orderCodeList);
        } else {
            orderByOrderId.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.PORTION_SHIPPED.getCode());//部分发货
            getSynchronousOrderDetail(orderByOrderId.getParentOrderCode(), expressNumber, expressCode, orderCodeList, orderDetailId);
        }

        orderByOrderId.setLastUpdateTime(date);
        orderByOrderId.setLastUpdateBy(userSession.getId());
        orderByOrderId.setShippingTime(date);

        MallOrderLogModel mallOrderLogModel = new MallOrderLogModel();
        mallOrderLogModel.setIsDelete(false);
        mallOrderLogModel.setOrderId(orderByOrderId.getId());
        mallOrderLogModel.setOrderCode(orderByOrderId.getOrderCode());
        mallOrderLogModel.setCreateTime(date);
        mallOrderLogModel.setCreateBy(userSession.getId().toString());
        mallOrderLogModel.setOrderType(OrderConstant.OrderLogType.CHILD.getCode());
        mallOrderLogModel.setOperationInformation(OrderStatusEmnu.ORDER_STATUS.CANCEL.getMsg());
        mallOrderLogModel.setOperationType(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
        cmsMallOrderLogService.save(mallOrderLogModel);//子
        orderByOrderId.setIsSplitTheParcel(BaseEnum.YesOrNoEnum.YES.getCode());
        save(orderByOrderId);


        //修改夫父订单信息
        MallOrderModel mallOrderModelByOrderCode = getOrderByOrderCode(orderByOrderId.getParentOrderCode());//父订单

        MallOrderLogModel mallOrderLogModel1 = new MallOrderLogModel();
        mallOrderLogModel1.setIsDelete(false);
        mallOrderLogModel1.setOrderId(mallOrderModelByOrderCode.getId());
        mallOrderLogModel1.setOrderCode(mallOrderModelByOrderCode.getOrderCode());
        mallOrderLogModel1.setCreateTime(date);
        mallOrderLogModel1.setCreateBy(userSession.getId().toString());
        mallOrderLogModel1.setOrderType(OrderConstant.OrderLogType.PARENT.getCode());
        mallOrderLogModel1.setOperationInformation(OrderStatusEmnu.ORDER_STATUS.CANCEL.getMsg());
        mallOrderLogModel1.setOperationType(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode());
        cmsMallOrderLogService.save(mallOrderLogModel1);//父订单日志表
        List<MallOrderModel> mallOrderModelList = getMallOrderModelByParentOrderCode(mallOrderModelByOrderCode.getOrderCode());//子订列表
        Boolean orderDecide = true; //用来判断商品是否全部发货

        for (MallOrderModel mallOrderModel1 : mallOrderModelList) {
            if (mallOrderModel1.getLogisticStatus() == null ||//等于null
                    mallOrderModel1.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.IN_THE_STOCK.getCode()) ||//备货中
                    mallOrderModel1.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode()) ||//待发货
                    mallOrderModel1.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.PORTION_SHIPPED.getCode())) {
                orderDecide = false;
                break;
            }
        }
        if (orderDecide) {
            mallOrderModelByOrderCode.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode());//全部发货
        } else {
            mallOrderModelByOrderCode.setLogisticStatus(OrderStatusEmnu.LOGISTIC_STATUS.PORTION_SHIPPED.getCode());//部分发货
        }


        mallOrderModelByOrderCode.setLastUpdateTime(date);
        mallOrderModelByOrderCode.setLastUpdateBy(userSession.getId());
        mallOrderModelByOrderCode.setShippingTime(date);
        mallOrderModelByOrderCode.setIsSplitTheParcel(BaseEnum.YesOrNoEnum.YES.getCode());
        save(mallOrderModelByOrderCode);//修改父订单
        return base.getSuccessMsg();
    }


    /**
     * 获取包裹号
     *
     * @param date
     * @return
     */
    private String getPackageCode(Date date) {
        String packageCodeString = null;
        String quantityString = null;
        String packageCode = null;
        synchronized (this) {
            packageCode = DatetimeUtil.getDateToString(date, "yyyyMMdd");
            Object quantity = redisUtil.getObject(packageCode);
            if (quantity == null) {
                quantity = 1L;
                quantityString = String.format("%04d", quantity);
            } else {
                quantityString = String.format("%04d", quantity);
                quantity = Long.valueOf(quantity.toString()) + 1L;
            }
            redisUtil.setObejct(packageCode, quantity);
        }
        packageCodeString = "YT" + packageCode + quantityString;
        OrderDeliveryPackageInfoModel orderDeliveryPackageInfoModelByPackageCode = cmsOrderDeliveryPackageInfoService.getOrderDeliveryPackageInfoModelByPackageCode(packageCodeString);
        if (orderDeliveryPackageInfoModelByPackageCode != null) {
            packageCodeString = getPackageCode(date);
        }
        return packageCodeString;
    }

    /**
     * 父订单code查询子订单列表
     *
     * @param orderCode
     * @return
     */
    private List<MallOrderModel> getMallOrderModelByParentOrderCode(String orderCode) {
        return queryFactory.select(Q).from(Q).where(Q.parentOrderCode.eq(orderCode)).fetch();
    }


    public void getOrderStreamList(Long shopId, Integer payType, Integer orderStatus, String staDate, String endDate, HttpServletRequest request, HttpServletResponse response) {
        OrderStreamVo orderStreamVo = new OrderStreamVo();
        Date startDate = null;
        if (StringUtils.isNotBlank(staDate)) {
            startDate = DateUtil.parseDate(staDate + " 00:00:00", DATE_TIME_PATTERN);
        }
        Date endDateTime = null;
        if (StringUtils.isNotBlank(endDate)) {
            endDateTime = DateUtil.parseDate(endDate + " 23:59:59", DATE_TIME_PATTERN);
        }
        orderStreamVo.setShopId(shopId);
        orderStreamVo.setPayType(payType);
        orderStreamVo.setOrderStatus(orderStatus);
        orderStreamVo.setStartTime(startDate);
        orderStreamVo.setEndTime(endDateTime);
        List<OrderStreamDto> allList = cmsPayStreamService.getPayStreamList(orderStreamVo);
        allList = allList.stream().map(p -> {
            OrderStreamDto orderStreamDto = new OrderStreamDto();
            BeanUtils.copyProperties(p, orderStreamDto);
            orderStreamDto.setPayTimeStr(DatetimeUtil.getDateToString(p.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
            return orderStreamDto;
        }).collect(Collectors.toList());
        JSONArray jsonArray = new JSONArray();
        jsonArray.fluentAddAll(allList);
        orderStreamExcel(request, response, jsonArray);
    }


    @Value("${shop_productDetails_url}")
    private String shopProductDetailsUrl;

    public void getOrderExport(Integer orderStatus, String staDate, String endDate, HttpServletRequest request, HttpServletResponse response) {
        PagedOutput<CmsMallOrderVo> cmsMallOrderVoPagedOutput = this.getOrderListByBean(new PagedInput(Integer.MAX_VALUE, 1), null, null, staDate, endDate, orderStatus, null);
        List<CmsMallOrderVo> orderListByBeanData = cmsMallOrderVoPagedOutput.getData();
        JSONArray jsonArray = new JSONArray();
        List<OrderExcelVo> orderExcelVoList = newArrayList();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }
        ShopInfoDto shopInfoById = cmsShopInfoService.getShopInfoById(userSession.getShopId());

        Long exportId = 0L;
        jsonArray.fluentAddAll(orderExcelVoList);
        String constantDataModelById = constantDataService.getConstantDataModelById(400L);//九洲导出
        String[] split = constantDataModelById.split(",");
        List<String> shopIds = Arrays.asList(split);
        String constantDataModelById1 = constantDataService.getConstantDataModelById(401L);//锦程导出
        String[] split1 = constantDataModelById1.split(",");
        List<String> shopIds1 = Arrays.asList(split1);
        String constantDataModelById2 = constantDataService.getConstantDataModelById(404L);//优来全球购导出
        String[] split2 = constantDataModelById2.split(",");
        List<String> shopIds2 = Arrays.asList(split2);


        if (shopIds != null && shopIds.contains(shopInfoById.getId().toString())) {
            exportId = 400L;
        } else if (shopIds1 != null && shopIds1.contains(shopInfoById.getId().toString())) {
            exportId = 401L;
        } else if (shopIds2 != null && shopIds2.contains(shopInfoById.getId().toString())) {
            exportId = 404L;
        } else {
            orderListByBeanData = Lists.newArrayList();
        }
        for (int number = 0; number < orderListByBeanData.size(); number++) {
            CmsMallOrderVo cmsMallOrderVo = orderListByBeanData.get(number);
            if (cmsMallOrderVo == null) {
                continue;   //记录错误信息
            }
            MallOrderModel orderByOrderId = getOrderByOrderId(cmsMallOrderVo.getId());
            if (orderByOrderId == null) {
                continue;   //记录错误信息
            }
            List<MallOrderDetailModel> orderDetailModelListByOrderId = cmsOrderDetailService.getOrderDetailModelListByOrderId(orderByOrderId.getId());
            if (orderDetailModelListByOrderId == null || orderDetailModelListByOrderId.size() < 0) {
                continue;
                //记录错误信息
            }
            String setLogistics = null;
            String setLogisticsNo = null;
            OrderExcelVo orderExcelVo = null;
            for (Integer index = 0; index < orderDetailModelListByOrderId.size(); index++) {
                MallOrderDetailModel mallOrderDetailModel = orderDetailModelListByOrderId.get(index);
                if (mallOrderDetailModel == null) {
                    continue;
                    //记录错误信息
                }
                orderExcelVo = new OrderExcelVo();
                if (index == 0) {
                    UserAddressManagementModel userAddressManagementModelById = appUserAddressService.getUserAddressManagementModelById(orderByOrderId.getOrderDeliveryAddressId());
                    if (userAddressManagementModelById == null) {
                        continue;
                        //记录错误信息
                    }
                    orderExcelVo.setNumber(number + 1); //序号
                    if (401L == exportId) {
                        orderExcelVo.setShipperName("HR-EX");//寄件人姓名
                        orderExcelVo.setShipperphone("9054796699");//寄件人电话
                    } else {
                        orderExcelVo.setShipperName(userAddressManagementModelById.getNickName());//寄件人姓名
                        orderExcelVo.setShipperphone(userAddressManagementModelById.getPhone());//寄件人电话
                    }
                    orderExcelVo.setNickName(userAddressManagementModelById.getNickName()); //收件人名称
                    orderExcelVo.setPhone(userAddressManagementModelById.getPhone());//收件人电话
                    orderExcelVo.setProvince(userAddressManagementModelById.getProvince());//收件人省
                    orderExcelVo.setCity(userAddressManagementModelById.getCity());//收件人城市
                    orderExcelVo.setArea(userAddressManagementModelById.getArea());  //收件人区
                    orderExcelVo.setAddress(userAddressManagementModelById.getAddress()); //收件人具体地址
                    orderExcelVo.setAddressDetails(userAddressManagementModelById.getProvince() + " " + userAddressManagementModelById.getCity() + " " + userAddressManagementModelById.getArea() + " " + userAddressManagementModelById.getAddress());
                    orderExcelVo.setCardNo(orderByOrderId.getBuyerCardNo());   //收件人身份证号码
                    orderExcelVo.setOrderCode(orderByOrderId.getOrderCode()); //电商订单号
                    orderExcelVo.setRemake(orderByOrderId.getRemake());    //备注
                    orderExcelVo.setOrderStatusStr(cmsMallOrderVo.getOrderStatusStr());
                }
                OrderDeliveryPackageModel orderPackage = orderDeliveryPackageService.getOrderPackage(mallOrderDetailModel.getId());
                //查询包裹信息
                if (orderPackage != null) {
                    if (orderPackage.getDeliveryId() != null) {
                        MallOrderDeliveryModel mallOrderDeliveryById = cmsOrderDeliveryService.getMallOrderDeliveryById(orderPackage.getDeliveryId());
                        if (mallOrderDeliveryById != null) {
                            if (setLogisticsNo != null) {
                                if (setLogisticsNo.equals(mallOrderDeliveryById.getDeliveryNo())) {

                                } else {
                                    orderExcelVo.setLogistics(mallOrderDeliveryById.getDeliveryCompanyCode()); //物流公司
                                    orderExcelVo.setLogisticsNo(mallOrderDeliveryById.getDeliveryNo());//运单号
                                }
                            } else {
                                orderExcelVo.setLogistics(mallOrderDeliveryById.getDeliveryCompanyCode()); //物流公司
                                orderExcelVo.setLogisticsNo(mallOrderDeliveryById.getDeliveryNo());//运单号
                                setLogistics = mallOrderDeliveryById.getDeliveryCompanyCode();
                                setLogisticsNo = mallOrderDeliveryById.getDeliveryNo();
                            }
                        }
                    }
                } else {
                    List<CmsOrderDeliveryVo> mallOrderDeliveryByOrderId = cmsOrderDeliveryService.getMallOrderDeliveryByOrderId(orderByOrderId.getId());
                    if (mallOrderDeliveryByOrderId != null && mallOrderDeliveryByOrderId.size() > 0) {
                        if (mallOrderDeliveryByOrderId.size() == 1) {
                            CmsOrderDeliveryVo cmsOrderDeliveryVo = mallOrderDeliveryByOrderId.get(0);
                            if (setLogisticsNo != null) {
                                if (setLogisticsNo.equals(cmsOrderDeliveryVo.getDeliveryNo())) {

                                } else {
                                    orderExcelVo.setLogistics(cmsOrderDeliveryVo.getDeliveryCompanyCode()); //物流公司
                                    orderExcelVo.setLogisticsNo(cmsOrderDeliveryVo.getDeliveryNo());//运单号
                                }
                            } else {
                                orderExcelVo.setLogistics(cmsOrderDeliveryVo.getDeliveryCompanyCode()); //物流公司
                                orderExcelVo.setLogisticsNo(cmsOrderDeliveryVo.getDeliveryNo());//运单号
                                setLogistics = cmsOrderDeliveryVo.getDeliveryCompanyCode();
                                setLogisticsNo = cmsOrderDeliveryVo.getDeliveryNo();
                            }
                        }
                    }
                }
                List<BaseProductCategoryModel> baseProductCategoryModelList = baseProductCategoryService.getBaseProductCategoryModelList();
                StringBuffer sb = new StringBuffer();
                if (baseProductCategoryModelList != null && baseProductCategoryModelList.size() > 0) {
                    for (BaseProductCategoryModel productCategoryModel : baseProductCategoryModelList) {
                        sb.append(productCategoryModel.getCategoryName()).append(",");
                    }
                }
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                }
                orderExcelVo.setChannel(sb.toString());//渠道
                ProductInfoModel productInfoById = productCmsService.getProductInfoById(mallOrderDetailModel.getProductId());
                orderExcelVo.setBrandName(productInfoById.getBrandName());//品牌
                if (400 == exportId) {
                    orderExcelVo.setChineseName(productInfoById.getProductName() + skuName(mallOrderDetailModel.getProductSkuId()));//中文品名 //商品名+sku值
                } else {
                    orderExcelVo.setChineseName(productInfoById.getProductName());
                }

                BaseProductCategoryModel productCategoryModel = baseProductCategoryService.BaseProductCategoryById(productInfoById.getCategoryId());
                orderExcelVo.setSpecification(skuName(mallOrderDetailModel.getProductSkuId()));
                orderExcelVo.setQuantity(mallOrderDetailModel.getQuantity());//数量
                orderExcelVo.setClassify(productCategoryModel.getCategoryName());
                StringBuffer stringBuffer = new StringBuffer(shopProductDetailsUrl);
                stringBuffer.append(productInfoById.getShopId());
                // placeholder / shopProductDetailsUrl
                orderExcelVo.setProductDetailsUrl(stringBuffer.toString().replace("#$%%^&", productInfoById.getId().toString()));

                String constantDataModelById3 = constantDataService.getConstantDataModelById(200L);
                BigDecimal multiply = null;
                if (400L == exportId) {
                    if (mallOrderDetailModel.getProductSalesPrice() == null || mallOrderDetailModel.getProductSalesPrice() < 1) {
                        multiply = new BigDecimal(0L);
                    } else {
                        Double aDouble = Double.valueOf(constantDataModelById3);
                        Double productSalesPrice = NumberUtil.centToYuanForDouble(mallOrderDetailModel.getProductSalesPrice());
                        multiply = new BigDecimal(productSalesPrice).divide(new BigDecimal(aDouble), 2, BigDecimal.ROUND_UP);
                    }
                } else {
                    multiply = new BigDecimal(NumberUtil.centToYuan(mallOrderDetailModel.getProductSalesPrice()));
                }

                orderExcelVo.setSalesPrice(multiply);//单价
                // orderExcelVo.setSpecification("");//规格
                orderExcelVo.setUnits("");//单位
                // orderExcelVo.setWeight("");//包裹重量
                //orderExcelVo.setInsurance("");//保险额
                //orderExcelVo.setPremium("");//保险费
                //orderExcelVo.setTariff("");//关税
                orderExcelVo.setRecipientZipCode("");//收件人邮编
                orderExcelVo.setTransshipmentCompany("");//国内转运公司
                orderExcelVo.setTranshipmentOrderNo("");//国内转运单号
                ProductSkuModel productSkuDtoById = productCmsSkuService.getProductSkuDtoById(mallOrderDetailModel.getProductSkuId());
                if (productSkuDtoById != null) {
                    orderExcelVo.setSkuCode(productSkuDtoById.getProductSkuCode());//SKU
                }
                if (401L == exportId) {
                    orderExcelVo.setOrderCode(orderByOrderId.getOrderCode()); //电商订单号
                }
                orderExcelVoList.add(orderExcelVo);
            }
        }
        jsonArray.fluentAddAll(orderExcelVoList);
        if (400L == exportId) {
            orderExcelByJiuZhou(request, response, jsonArray, shopInfoById.getShopName());
        } else if (401L == exportId) {
            orderExcelByJinCheng(request, response, jsonArray, shopInfoById.getShopName());
        } else if (404L == exportId) {
            orderExcelByYouLai(request, response, jsonArray, shopInfoById.getShopName());
        } else {
            orderExcelByJiuZhou(request, response, jsonArray, shopInfoById.getShopName());
        }

    }

    private void orderExcelByYouLai(HttpServletRequest request, HttpServletResponse response, JSONArray jsonArray, String shopName) {
        String nowDate = DateUtils.nowDate("yyyyMMddHHmmss");
        //excel文件名
        String fileName = shopName + "-" + nowDate + ".xlsx";
        //sheet名
        String sheetName = "sheet1";
        //响应到客户端
        try {
            this.setResponseHeader(request, response, fileName);
            OutputStream os = response.getOutputStream();
            ExcelConverter excelConverter = ExcelConverter.forXlsx();
            DataTable dataTable = new DataTable(sheetName);
            List<DataColumn> columns = new ArrayList<>();
            // sb.replace(3, 7, str);
            columns.add(new DataColumn("orderCode", "订单号"));
            columns.add(new DataColumn("productDetailsUrl", "桃店商品详情URL"));//https://m.1taolife.com/#/detail/normal/6286?shopId=46
            columns.add(new DataColumn("chineseName", "商品名"));
            columns.add(new DataColumn("classify", "基础分类"));
            columns.add(new DataColumn("brandName", "品牌"));
            columns.add(new DataColumn("specification", "sku名称"));
            columns.add(new DataColumn("salesPrice", "单价"));
            columns.add(new DataColumn("quantity", "数量"));
            columns.add(new DataColumn("nickName", "收货人姓名"));
            columns.add(new DataColumn("phone", "手机号"));
            columns.add(new DataColumn("addressDetails", "地址"));
            columns.add(new DataColumn("cardNo", "身份证"));
            columns.add(new DataColumn("orderStatusStr", "订单状态"));


           /* columns.add(new DataColumn("logisticsNo", "运单号"));
            columns.add(new DataColumn("channel", "渠道"));
            columns.add(new DataColumn("shipperName", "寄件人姓名"));
            columns.add(new DataColumn("shipperphone", "寄件人电话"));
            columns.add(new DataColumn("chineseName", "中文品名"));
            // columns.add(new DataColumn("productSkuName", "商品名+sku值"));
            columns.add(new DataColumn("units", "单位"));
            columns.add(new DataColumn("weight", "包裹重量(LBS)"));
            columns.add(new DataColumn("insurance", "保险额"));
            columns.add(new DataColumn("premium", "保险费"));
            columns.add(new DataColumn("tariff", "关税"));
            columns.add(new DataColumn("province", "收件人省份"));
            columns.add(new DataColumn("city", "收件人城市"));
            columns.add(new DataColumn("area", "收件人区/县"));
            columns.add(new DataColumn("recipientZipCode", "收件人邮编"));
            columns.add(new DataColumn("transshipmentCompany", "国内转运公司"));
            columns.add(new DataColumn("transhipmentOrderNo", "国内转运单号"));
            columns.add(new DataColumn("orderCode", "订单号"));
            columns.add(new DataColumn("skuCode", "SKU"));
            columns.add(new DataColumn("remake", "备注"));*/
            dataTable.addColumns(columns);
            excelConverter.export(os, dataTable, jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel"); // 保存为excel
            response.setHeader("Content-Disposition", "attachment;" + ExcelExportUtil.getFileName(request, fileName));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void orderExcelByJiuZhou(HttpServletRequest request, HttpServletResponse response, JSONArray jsonArray, String shopName) {

        String nowDate = DateUtils.nowDate("yyyyMMddHHmmss");
        //excel文件名
        String fileName = shopName + "-" + nowDate + ".xlsx";
        //sheet名
        String sheetName = "sheet1";
        //响应到客户端
        try {
            this.setResponseHeader(request, response, fileName);
            OutputStream os = response.getOutputStream();
            ExcelConverter excelConverter = ExcelConverter.forXlsx();
            DataTable dataTable = new DataTable(sheetName);
            List<DataColumn> columns = new ArrayList<>();
            columns.add(new DataColumn("number", "序号"));
            //columns.add(new DataColumn("orderCode", "订单号"));
            columns.add(new DataColumn("logistics", "快递公司"));
            columns.add(new DataColumn("logisticsNo", "运单号"));
            columns.add(new DataColumn("channel", "渠道"));
            columns.add(new DataColumn("shipperName", "寄件人姓名"));
            columns.add(new DataColumn("shipperphone", "寄件人电话"));
            columns.add(new DataColumn("brandName", "品牌"));
            columns.add(new DataColumn("chineseName", "中文品名"));
            // columns.add(new DataColumn("productSkuName", "商品名+sku值"));
            columns.add(new DataColumn("quantity", "数量"));
            columns.add(new DataColumn("salesPrice", "单价（美金）"));
            columns.add(new DataColumn("specification", "规格"));
            columns.add(new DataColumn("units", "单位"));
            columns.add(new DataColumn("weight", "包裹重量(LBS)"));
            columns.add(new DataColumn("insurance", "保险额"));
            columns.add(new DataColumn("premium", "保险费"));
            columns.add(new DataColumn("tariff", "关税"));
            columns.add(new DataColumn("nickName", "收件姓名"));
            columns.add(new DataColumn("phone", "收件人电话"));
            columns.add(new DataColumn("province", "收件人省份"));
            columns.add(new DataColumn("city", "收件人城市"));
            columns.add(new DataColumn("area", "收件人区/县"));
            columns.add(new DataColumn("address", "收件人具体地址"));
            columns.add(new DataColumn("recipientZipCode", "收件人邮编"));
            columns.add(new DataColumn("cardNo", "收件人身份证号码"));
            columns.add(new DataColumn("transshipmentCompany", "国内转运公司"));
            columns.add(new DataColumn("transhipmentOrderNo", "国内转运单号"));
            columns.add(new DataColumn("orderCode", "电商订单号"));
            columns.add(new DataColumn("skuCode", "SKU"));
            columns.add(new DataColumn("remake", "备注"));
            dataTable.addColumns(columns);
            excelConverter.export(os, dataTable, jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void orderExcelByJinCheng(HttpServletRequest request, HttpServletResponse response, JSONArray jsonArray, String shopName) {

        String nowDate = DateUtils.nowDate("yyyyMMddHHmmss");
        //excel文件名
        String fileName = shopName + "-" + nowDate + ".xlsx";
        //sheet名
        String sheetName = "sheet1";
        //响应到客户端
        try {
            this.setResponseHeader(request, response, fileName);
            OutputStream os = response.getOutputStream();
            ExcelConverter excelConverter = ExcelConverter.forXlsx();
            DataTable dataTable = new DataTable(sheetName);
            List<DataColumn> columns = new ArrayList<>();
            //columns.add(new DataColumn("number", "序号"));
            columns.add(new DataColumn("orderCode", "订单号"));
            columns.add(new DataColumn("logistics", "快递公司"));
            columns.add(new DataColumn("logisticsNo", "运单号"));
            columns.add(new DataColumn("customOrderMumber", "自定义单号"));
            columns.add(new DataColumn("hostCustomOrderMumber", "主订单分组编号"));
            columns.add(new DataColumn("path", "路线"));
            columns.add(new DataColumn("shipperName", "发货人"));
            columns.add(new DataColumn("shipperphone", "发货人电话"));
            columns.add(new DataColumn("shipperCompany", "发货人公司"));
            columns.add(new DataColumn("nickName", "收件人"));
            columns.add(new DataColumn("phone", "手机号"));
            columns.add(new DataColumn("phoneNumber", "座机号"));
            columns.add(new DataColumn("cardNo", "身份证"));
            columns.add(new DataColumn("address", "地址"));
            columns.add(new DataColumn("province", "省份"));
            columns.add(new DataColumn("city", "城市"));
            columns.add(new DataColumn("area", "地区"));
            columns.add(new DataColumn("zipCode", "邮编"));
            columns.add(new DataColumn("chineseName", "商品名称"));
            columns.add(new DataColumn("barCode", "条形码"));
            columns.add(new DataColumn("classify", "分类"));
            columns.add(new DataColumn("brandName", "品牌"));
            columns.add(new DataColumn("specification", "规格"));
            columns.add(new DataColumn("quantity", "数量"));
            columns.add(new DataColumn("weight", "重量(磅)"));
            columns.add(new DataColumn("value", "价值"));
            columns.add(new DataColumn("packageWeight", "包裹重量(磅)"));
            columns.add(new DataColumn("packageSize", " 包裹尺寸(英寸)"));
            columns.add(new DataColumn("remake", "备注"));
            columns.add(new DataColumn("skuCode", "SKU"));
            dataTable.addColumns(columns);
            excelConverter.export(os, dataTable, jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void orderStreamExcel(HttpServletRequest request, HttpServletResponse response, JSONArray jsonArray) {

        String nowDate = DateUtils.nowDate("yyyyMMddHHmmss");
        //excel文件名
        String fileName = "orderStream" + "-" + nowDate + ".xlsx";
        //sheet名
        String sheetName = "sheet1";
        //响应到客户端
        try {
            this.setResponseHeader(request, response, fileName);
            OutputStream os = response.getOutputStream();
            ExcelConverter excelConverter = ExcelConverter.forXlsx();
            DataTable dataTable = new DataTable(sheetName);
            List<DataColumn> columns = new ArrayList<>();
            columns.add(new DataColumn("pOrderCode", "订单号"));
            columns.add(new DataColumn("payTradeNo", "流水号"));
            columns.add(new DataColumn("payTimeStr", "支付时间"));
            columns.add(new DataColumn("orgCurrency", "原币种"));
            columns.add(new DataColumn("tarCurrency", "目标币种"));
            columns.add(new DataColumn("actualAmount", "人民币金额"));
            columns.add(new DataColumn("refundFee", "退款金额"));
            columns.add(new DataColumn("outFee", "外币金额"));
            columns.add(new DataColumn("cardType", "证件类型"));
            columns.add(new DataColumn("cardNo", "证件号码"));
            columns.add(new DataColumn("realName", "姓名"));
            columns.add(new DataColumn("productName", "商品名称"));
            dataTable.addColumns(columns);
            excelConverter.export(os, dataTable, jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String skuName(Long productSkuId) {
        StringBuffer sb = new StringBuffer();
        if (productSkuId != null) {
            ProductSkuModel productSkuModel = productCmsSkuService.getProductSkuDtoById(productSkuId);
            if (productSkuModel != null) {

                if (productSkuModel.getParentId() != null) {
                    ProductSkuModel productParentSkuModel = productCmsSkuService.getProductSkuDtoById(productSkuModel.getParentId());
                    if (productParentSkuModel != null && StringUtils.isNotEmpty(productParentSkuModel.getAttrSpecValue())) {
                        sb.append(productParentSkuModel.getAttrSpecValue()).append("/");
                    }
                }
                if (productSkuModel.getAttrSpecValue() != null) {
                    sb.append(productSkuModel.getAttrSpecValue());
                }
            }
        }
        return sb.toString();
    }

    @Transactional
    public DataOutput getOrderImporJiuZhou(MultipartFile file, OperationUserCmsModel userSession, HttpServletRequest request) {

        List<OrderExcelVo> orderExcelVoList = Lists.newArrayList();
        Sheet rows = ExcelExportUtil.orderImport(file);
        for (int i = 1; i <= rows.getLastRowNum(); i++) {
            Row row = rows.getRow(i);//获取第i行数据
            if (StringUtils.isEmpty(ExcelExportUtil.cellType(row.getCell(27)))) {
                break;
            }
            OrderExcelVo orderExcelVo = new OrderExcelVo();
            String number = ExcelExportUtil.cellType(row.getCell(0)).trim();
            if (!StringUtils.isEmpty(number)) {
                orderExcelVo.setNumber(Integer.valueOf(number)); //序号
            }
            String logistics = ExcelExportUtil.cellType(row.getCell(1)).trim();
            logistics.matches("[0-9]+");
            if (!StringUtils.isBlank(logistics)) {
                logistics = logistics.trim();
                logistics.matches("[0-9]+");
                if (!StringUtils.isEmpty(logistics)) {
                    boolean matches = logistics.matches("[0-9]+");
                    ServicesCompanyInfoModel servicesCompanyInfoModelById = null;
                    if (matches) {
                        servicesCompanyInfoModelById = cmsServicesCompanyInfoService.getServicesCompanyInfoModelById(Long.valueOf(logistics));
                    }
                    if (!matches && servicesCompanyInfoModelById == null) {
                        servicesCompanyInfoModelById = cmsServicesCompanyInfoService.getServicesCompanyInfoByNameabbr(logistics);
                    }
                    if (servicesCompanyInfoModelById == null) {
                        return base.getErrorMsg("物流公司参数 = 【" + logistics + "】 查询不到物流信息请确认");
                    }
                    orderExcelVo.setLogistics(servicesCompanyInfoModelById.getId().toString());
                    orderExcelVo.setLogisticsCode(servicesCompanyInfoModelById.getNameAbbr());
                    orderExcelVo.setLogisticsName(servicesCompanyInfoModelById.getCompanyName());
                    //     orderExcelVo.setLogistics(ExcelExportUtil.cellType(row.getCell(2)).trim());      //物流公司
                }
            }
            String logisticsNo = ExcelExportUtil.cellType(row.getCell(2));
            if (!StringUtils.isBlank(logisticsNo)) {
                orderExcelVo.setLogisticsNo(logisticsNo.trim());
            }
            orderExcelVo.setChannel(ExcelExportUtil.cellType(row.getCell(3)).trim());//渠道
            orderExcelVo.setShipperName(ExcelExportUtil.cellType(row.getCell(4)).trim());//寄件人姓名
            orderExcelVo.setShipperphone(ExcelExportUtil.cellType(row.getCell(5)).trim());//寄件人电话
            orderExcelVo.setBrandName(ExcelExportUtil.cellType(row.getCell(6)).trim()); //品牌
            orderExcelVo.setChineseName(ExcelExportUtil.cellType(row.getCell(7)).trim());  //中文品名 商品名+sku值
            /*String quantity = ExcelExportUtil.cellType(row.getCell(8)).trim(); //数量
            if (!StringUtils.isEmpty(quantity)) {
                orderExcelVo.setQuantity(Integer.valueOf(quantity));
            }*/
            //单价
         /*   String salesPrice = ExcelExportUtil.cellType(row.getCell(9)).trim();
            if (salesPrice != null) {
                orderExcelVo.setSalesPrice(new BigDecimal(Double));
            }*/
            //规格
            //private String specification;//空 10
            //单位
            //private String units; //空11
            //包裹重量
            //private Double weight; //空12
            //保险额
            //private BigDecimal insurance;//空13
            //保险费
            //rivate BigDecimal premium;//空14
            //关税
            //private BigDecimal tariff;//空15
            //收件人名称
            //private String nickName;//16
            //收件人电话
            //private String phone;17
            //收件人省
            //private String province;18
            //收件人城市
            //private String city;19
            //收件人区
            //private String area;20
            //收件人具体地址
            //private String address;21
            //收件人邮编
            //private String recipientZipCode;//空22
            //收件人身份证号码
            //private String cardNo;//23
            //国内转运公司
            //private String transshipmentCompany;//空24
            //国内转运单号
            //private String transhipmentOrderNo;//空25
            //电商订单号
            String orderCode = ExcelExportUtil.cellType(row.getCell(26)).trim();//订单id
          /*  if (orderCode == null) {
                return base.getErrorMsg(" 第" + i + "行 查询不到订单编号不完整请确认参数是否正确");
            }*/
            if (StringUtils.isNotEmpty(orderCode)) {
                MallOrderModel orderByOrderCode = getOrderByOrderCode(orderCode);
                if (orderByOrderCode == null) {
                    return base.getErrorMsg(" 第" + i + "行 订单编号【" + orderCode + "】  查询不到订单信息请确认参数是否正确");
                }
                if (!orderByOrderCode.getShopId().equals(userSession.getShopId())) {
                    return base.getErrorMsg(" 第" + i + "行 订单信息不属于您  无权限修改");
                }
            }
            orderExcelVo.setOrderCode(orderCode);
            String skuCode = ExcelExportUtil.cellType(row.getCell(27));
            ProductSkuModel productCmsSku = productCmsSkuService.getProductCmsSku(skuCode);
            if (productCmsSku == null) {
                return base.getErrorMsg(" 第" + i + "行 商品SKU编号【" + skuCode + "】  查询不到订单信息请确认参数是否正确");
            }
            if (skuCode == null) {
                return base.getErrorMsg(" 第" + i + "行 查询不到商品SKU不完整请确认参数是否正确");
            }
            orderExcelVo.setSkuCode(skuCode);
            orderExcelVoList.add(orderExcelVo);
        }
        if (orderExcelVoList.size() <= 0) {
            return base.getSuccessMsg();
        }
        //执行update操作
        updateOrderImporInfo(orderExcelVoList, userSession);


        return base.getSuccessMsg();
    }

    @Transactional
    public DataOutput updateOrderImporInfo(List<OrderExcelVo> orderExcelVoList, OperationUserCmsModel userSession) throws RuntimeException {

        List<OrderExcelListVo> orderExcelListVos = newArrayList();
        OrderExcelListVo orderExcelListVo = null;
        List<OrderExcelVo> orderExcelVoList1 = Lists.newArrayList(); //一组订单
        for (OrderExcelVo orderExcelVo : orderExcelVoList) {
            if (orderExcelListVo != null && orderExcelListVo.getOrderCode().equals(orderExcelVo.getOrderCode())) {
                orderExcelVo.setOrderCode(null);
            }
            //先判断运单号是否存在是否需要发货
            if (StringUtils.isNotEmpty(orderExcelVo.getOrderCode())) {
                if (orderExcelListVo != null) {
                    List<OrderExcelVo> objects = newArrayList();
                    objects.addAll(orderExcelVoList1);
                    orderExcelListVo.setOrderExcelVoList(objects);
                    orderExcelListVos.add(orderExcelListVo);
                }
                orderExcelListVo = new OrderExcelListVo();
                //如果是新的订单 全部重置数据
                orderExcelVoList1 = Lists.newArrayList(); //一组订单
                orderExcelListVo.setLogistics(orderExcelVo.getLogistics());
                orderExcelListVo.setLogisticsCode(orderExcelVo.getLogisticsCode());
                orderExcelListVo.setLogisticsNo(orderExcelVo.getLogisticsNo());
                orderExcelListVo.setOrderCode(orderExcelVo.getOrderCode());
                orderExcelVo.setLogisticsName(null); //参数
                orderExcelVo.setLogisticsCode(null);
                orderExcelVo.setOrderCode(null);
                orderExcelVo.setLogisticsNo(null);
                orderExcelVoList1.add(orderExcelVo);
                continue;
            }
            if (StringUtils.isNotEmpty(orderExcelVo.getLogisticsNo())) {
                if (orderExcelListVo != null) {
                    orderExcelListVo.setIsSplitTheParcel(true);//标记拆包裹
                }
            }
            orderExcelVoList1.add(orderExcelVo);
        }
        orderExcelListVo.setOrderExcelVoList(orderExcelVoList1);
        orderExcelListVos.add(orderExcelListVo);
        if (orderExcelListVos != null && orderExcelListVos.size() > 0) {
            for (OrderExcelListVo excelListVo : orderExcelListVos) {
                if (StringUtils.isEmpty(excelListVo.getOrderCode())) {
                    continue;
                }
                if (StringUtils.isEmpty(excelListVo.getLogisticsNo())) {
                    continue;
                }
                MallOrderModel orderByOrderCode = getOrderByOrderCode(excelListVo.getOrderCode());
                if (orderByOrderCode == null) {
                    continue;
                    // throw new RuntimeException("【" + shopInfoById.getShopName() + "】查询不到 orderCode = " + excelListVo.getOrderCode() + "数据");
                }
                if (!orderByOrderCode.getPayStatus().equals(OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode())) {
                    continue;
                    //throw new RuntimeException("【" + shopInfoById.getShopName() + "】 orderCode = " + excelListVo.getOrderCode() + "订单未支付不可发货");
                }
                if (orderByOrderCode.getOrderStatus().equals(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode())) {
                    //订单取消 拒绝发货
                    continue;
                }
                if (orderByOrderCode.getOrderStatus().equals(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode())) {
                    //订单取消 拒绝发货
                    continue;
                }
                if (orderByOrderCode.getRefundStatus() != null) {
                    if (orderByOrderCode.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.APPLYING_FOR_REFUND.getCode()) ||
                            orderByOrderCode.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.REFUND.getCode()) ||
                            orderByOrderCode.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.NOT_REFUND.getCode())) {
                        //退款订单 不做处理
                        continue;
                    }
                }
                if (orderByOrderCode.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode()) && !excelListVo.getIsSplitTheParcel()) {//订单待发货 并没有拆单情况
                    orderDeliver(orderByOrderCode.getId(), excelListVo.getLogisticsNo(), Integer.valueOf(excelListVo.getLogistics()), request, null);//订单发货
                } else if (orderByOrderCode.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.WAIT_SHIP.getCode()) && excelListVo.getIsSplitTheParcel()) { //有拆单情况的
                    List<OrderExcelVo> orderExcelVoList2 = excelListVo.getOrderExcelVoList();
                    for (OrderExcelVo orderExcelVo : orderExcelVoList2) {
                        if (StringUtils.isNotEmpty(orderExcelVo.getLogisticsNo())) {
                            //订单详细信息
                            ProductSkuModel productCmsSku = productCmsSkuService.getProductCmsSku(orderExcelVo.getSkuCode());
                            MallOrderDetailModel mallOrderDetailModelByOrderIdAndSkuId = cmsOrderDetailService.getMallOrderDetailModelByOrderIdAndSkuId(orderByOrderCode.getId(), productCmsSku.getId());
                            if (mallOrderDetailModelByOrderIdAndSkuId == null) {
                                continue;
                            }
                            if (mallOrderDetailModelByOrderIdAndSkuId.getIsOutStock() != null && mallOrderDetailModelByOrderIdAndSkuId.getIsOutStock()) {
                                //缺货不发货
                                continue;
                            }
                            if (mallOrderDetailModelByOrderIdAndSkuId.getLogisticStatus() != null && mallOrderDetailModelByOrderIdAndSkuId.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.HAVE_BEEN_SIGNED.getCode())) {
                                //已签收不考虑修改
                                continue;
                            }
                            //单商品发货
                            partOfTheShipment(mallOrderDetailModelByOrderIdAndSkuId.getId(), orderExcelVo.getLogisticsNo(), Integer.valueOf(orderExcelVo.getLogistics()), request, null);
                        }
                    }
                    orderDeliver(orderByOrderCode.getId(), excelListVo.getLogisticsNo(), Integer.valueOf(excelListVo.getLogistics()), request, null);//订单发货
                } else if (orderByOrderCode.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode()) && !excelListVo.getIsSplitTheParcel()) {
                    //订单已经发货  切没有拆单情况
                    List<CmsOrderDeliveryVo> mallOrderDeliveryByOrderId = cmsOrderDeliveryService.getMallOrderDeliveryByOrderId(orderByOrderCode.getId());
                    CmsOrderDeliveryVo cmsOrderDeliveryVo = null;
                    if (mallOrderDeliveryByOrderId != null && mallOrderDeliveryByOrderId.size() != 0) {
                        cmsOrderDeliveryVo = mallOrderDeliveryByOrderId.get(0);
                    }
                    if (cmsOrderDeliveryVo == null) {
                        continue;
                    }
                    MallOrderDeliveryModel mallOrderDeliveryById = cmsOrderDeliveryService.getMallOrderDeliveryById(cmsOrderDeliveryVo.getId());
                    if (mallOrderDeliveryById == null) {
                        continue;
                    }

                    if (cmsOrderDeliveryVo.getDeliveryNo().equals(excelListVo.getLogisticsNo()) && cmsOrderDeliveryVo.getDeliveryCompanyCode().equals(excelListVo.getLogisticsCode())) {
                        //相同不做修改
                        continue;
                    }

                    ServicesCompanyInfoModel servicesCompanyInfoByNameabbr = cmsServicesCompanyInfoService.getServicesCompanyInfoByNameabbr(excelListVo.getLogisticsCode());
                    OrderDeliveryUpdateLogModel orderDeliveryUpdateLogModel = new OrderDeliveryUpdateLogModel();
                    orderDeliveryUpdateLogModel.setCreateBy(userSession.getId());
                    orderDeliveryUpdateLogModel.setCreatePhone(userSession.getPhone());
                    orderDeliveryUpdateLogModel.setCreateTime(new Date());
                    orderDeliveryUpdateLogModel.setIsDelete(false);
                    orderDeliveryUpdateLogModel.setOrderDeliveryId(mallOrderDeliveryById.getId());
                    orderDeliveryUpdateLogModel.setShopId(mallOrderDeliveryById.getShopId());
                    orderDeliveryUpdateLogModel.setNewDeliveryCompanyCode(servicesCompanyInfoByNameabbr.getNameAbbr());
                    orderDeliveryUpdateLogModel.setNewDeliveryCompanyName(servicesCompanyInfoByNameabbr.getCompanyName());
                    orderDeliveryUpdateLogModel.setNewDeliveryNo(excelListVo.getLogisticsNo());
                    orderDeliveryUpdateLogModel.setOldDeliveryCompanyCode(cmsOrderDeliveryVo.getDeliveryCompanyCode());
                    orderDeliveryUpdateLogModel.setOldDeliveryCompanyName(cmsOrderDeliveryVo.getDeliveryCompanyName());
                    orderDeliveryUpdateLogModel.setOldDeliveryNo(cmsOrderDeliveryVo.getDeliveryNo());
                    orderDeliveryUpdateLogModel.setOrderId(orderByOrderCode.getId());
                    orderDeliveryUpdateLogModel.setOrderCode(orderByOrderCode.getOrderCode());
                    orderDeliveryUpdateLogService.save(orderDeliveryUpdateLogModel);
                    //查询出物流信息
                    mallOrderDeliveryById.setLastUpdateTime(new Date());
                    mallOrderDeliveryById.setLastUpdateBy(userSession.getId());
                    mallOrderDeliveryById.setDeliveryCompanyName(servicesCompanyInfoByNameabbr.getCompanyName());
                    mallOrderDeliveryById.setDeliveryCompanyCode(servicesCompanyInfoByNameabbr.getNameAbbr());
                    mallOrderDeliveryById.setDeliveryNo(excelListVo.getLogisticsNo());
                    //修改物流信息
                    cmsOrderDeliveryService.save(mallOrderDeliveryById);
                    // TODO
                    UserAddressManagementModel userAddressManagementModelById = appUserAddressService.getUserAddressManagementModelById(orderByOrderCode.getOrderDeliveryAddressId());
                    if (kuaidi100Status) {
                        kuaidi100CmsService.subscribeData(mallOrderDeliveryById.getDeliveryCompanyCode(), mallOrderDeliveryById.getDeliveryNo(), userAddressManagementModelById.getPhone());
                    }
                }
            }
        }
        return base.getSuccessMsg();
    }

    @Transactional
    public String updateOrderLogisticTaskModel(MallOrderDeliveryModel mallOrderDeliveryModel) {
        List<OrderLogisticTaskModel> orderLogisticTaskModelList = cmsOrderLogisticaskService.getOrderLogisticTaskModelByLogisticCodeAndLogisticNumber(mallOrderDeliveryModel);
        if (orderLogisticTaskModelList != null && orderLogisticTaskModelList.size() > 0) {
            return "相同物流单号  不需要爬虫";
        }
        OrderLogisticTaskModel orderLogisticTaskModel = new OrderLogisticTaskModel();
        orderLogisticTaskModel.setCreateBy(mallOrderDeliveryModel.getCreateBy());
        orderLogisticTaskModel.setCreateTime(mallOrderDeliveryModel.getCreateTime());
        orderLogisticTaskModel.setIsClose(false);
        orderLogisticTaskModel.setLogisticCode(mallOrderDeliveryModel.getDeliveryCompanyCode());
        orderLogisticTaskModel.setLogisticName(mallOrderDeliveryModel.getDeliveryCompanyName());
        orderLogisticTaskModel.setLogisticNumber(mallOrderDeliveryModel.getDeliveryNo());
        orderLogisticTaskModel.setShopId(mallOrderDeliveryModel.getShopId());
        cmsOrderLogisticaskService.save(orderLogisticTaskModel);
        return "爬取数据";
    }


    @Transactional
    public DataOutput applyRefund(CmsOrderApplyRefundVo cmsOrderApplyRefundVo) {

        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }
        //先查询订单信息
        if (cmsOrderApplyRefundVo == null) {
            return base.getErrorMsg("请求参数为空");
        }
        if (cmsOrderApplyRefundVo.getOrderId() == null) {
            return base.getErrorMsg("请选择申请订单");
        }
        MallOrderModel mallOrderModel = getOrderByOrderId(cmsOrderApplyRefundVo.getOrderId());
        if (mallOrderModel == null) {
            return base.getErrorMsg("查询不到订单信息");
        }

        if (cmsOrderApplyRefundVo.getApplicationsAmount() == null) {
            return base.getErrorMsg("请输入退款金额");
        }
        //判断订单还能进行退款操作么
        Integer refund = isRefund(cmsOrderApplyRefundVo.getOrderId());
        if (refund < BaseEnum.YesOrNoEnum.YES.getCode()) {
            return base.getErrorMsg("当前订单不能申请退款");
        }

        verifyProductQuantity(cmsOrderApplyRefundVo.getCmsOrderApplyRefundDetailsVoList());

        Long refundFee = cmsOrderApplyRefundVo.getApplicationsAmount().multiply(new BigDecimal(100L)).longValue();
        if (refundFee < 1) {
            return base.getErrorMsg("金额有误  金额不能小于一分钱");
        }
        if (refundFee > mallOrderModel.getActualAmount()) {
            return base.getErrorMsg("金额有误  金额不能超过订单支付金额");
        }

        Date date = new Date();


        Integer refundType = OrderStatusEmnu.REFUND_TYPE.ORDINARY_REFUND.getKey();//默认整单

        Integer refundReason = OrderStatusEmnu.REFUND_REASON.OTHER.getKey(); //默认其他

        //APPLYING_FOR_REFUND(-10, "申请退款中"),
        //PORTION_APPLYING_FOR_REFUND(-11, "部分申请退款中"),
        Integer refundStatus = OrderStatusEmnu.REFUND_STATUS.APPLYING_FOR_REFUND.getCode();//默认申请退款中
        //开始创建退款信息
        OrderShopRefundLogModel orderShopRefundLogModel = new OrderShopRefundLogModel();
        orderShopRefundLogModel.setCreateBy(userSession.getCreateBy());
        orderShopRefundLogModel.setCreateName(userSession.getPhone());
        orderShopRefundLogModel.setCreateTime(date);
        orderShopRefundLogModel.setIsDelete(false);
        orderShopRefundLogModel.setShopId(userSession.getShopId());
        orderShopRefundLogModel.setOrderId(mallOrderModel.getId());
        orderShopRefundLogModel.setRefundFee(cmsOrderApplyRefundVo.getApplicationsAmount().multiply(new BigDecimal(100L)).longValue());//金额
        orderShopRefundLogModel.setOrderCode(mallOrderModel.getOrderCode());
        MallOrderRefundModel mallOrderRefundModel = new MallOrderRefundModel();
        mallOrderRefundModel.setRefundFee(refundFee);
        mallOrderRefundModel.setBuyerId(mallOrderModel.getBuyerUserId());
        mallOrderRefundModel.setCreateBy(-1L);
        mallOrderRefundModel.setOrderCode(mallOrderModel.getOrderCode());
        mallOrderRefundModel.setOrderId(mallOrderModel.getId());

        mallOrderRefundModel.setRefundReason(refundReason);
        UserInfoModel appUserInfoByUserId = appUserService.getAppUserInfoByUserId(mallOrderModel.getBuyerUserId());
        if (appUserInfoByUserId == null) {
            return base.getErrorMsg("用户不存在 ");
        }

        //mallOrderRefundModel.setRefundDescription(null);
        mallOrderRefundModel.setPhone(appUserInfoByUserId.getPhone());

        List<CmsOrderApplyRefundDetailsVo> cmsOrderApplyRefundDetailsVoList = cmsOrderApplyRefundVo.getCmsOrderApplyRefundDetailsVoList();
        /**
         * 判断整单还是部分
         */
        if (cmsOrderApplyRefundDetailsVoList != null && cmsOrderApplyRefundDetailsVoList.size() > 0) {
            //查询订单有多少个商品
            List<MallOrderDetailModel> orderDetailModelListByOrderId = cmsOrderDetailService.getOrderDetailModelListByOrderId(cmsOrderApplyRefundVo.getOrderId());

            if (orderDetailModelListByOrderId.size() == cmsOrderApplyRefundDetailsVoList.size()) {
                for (CmsOrderApplyRefundDetailsVo cmsOrderApplyRefundDetailsVo : cmsOrderApplyRefundDetailsVoList) {
                    MallOrderDetailModel mallOrderDetailModel = cmsOrderDetailService.getMallOrderDetailModelById(cmsOrderApplyRefundDetailsVo.getId());
                    if (cmsOrderApplyRefundDetailsVo.getQuantity() < mallOrderDetailModel.getQuantity()) {
                        //部分退款
                        refundType = OrderStatusEmnu.REFUND_TYPE.STOCK_OUT_REFUND.getKey(); //缺货
                        refundStatus = OrderStatusEmnu.REFUND_STATUS.PORTION_APPLYING_FOR_REFUND.getCode();//部分退款中
                        break;
                    }
                }
            } else {
                refundType = OrderStatusEmnu.REFUND_TYPE.STOCK_OUT_REFUND.getKey(); //缺货
                refundStatus = OrderStatusEmnu.REFUND_STATUS.PORTION_APPLYING_FOR_REFUND.getCode();//部分退款中

            }

        }

        mallOrderRefundModel.setRefundType(refundType);
        mallOrderRefundModel.setRefundStatus(OrderStatusEmnu.REFUND_STATUS.APPLYING_FOR_REFUND.getCode());
        mallOrderRefundModel.setIsDelete(false);
        mallOrderRefundModel.setCreateTime(date);

        MallOrderRefundModel save = cmsMallOrderRefundService.save(mallOrderRefundModel);//退款信息表
        if (refundType.equals(OrderStatusEmnu.REFUND_TYPE.STOCK_OUT_REFUND.getKey())) {
            List<MallOrderRefundDetailModel> mallOrderRefundDetailModelList = newArrayList();
            //当为缺货退款  构建退款商品
            MallOrderRefundDetailModel mallOrderRefundDetailModel = null;
            for (CmsOrderApplyRefundDetailsVo cmsOrderApplyRefundDetailsVo : cmsOrderApplyRefundDetailsVoList) {
                mallOrderRefundDetailModel = new MallOrderRefundDetailModel();
                MallOrderDetailModel mallOrderDetailModel = cmsOrderDetailService.getMallOrderDetailModelById(cmsOrderApplyRefundDetailsVo.getId());
                mallOrderRefundDetailModel.setRefundId(save.getId());
                mallOrderRefundDetailModel.setOrderDetailId(mallOrderDetailModel.getId());
                mallOrderRefundDetailModel.setCreateTime(date);
                mallOrderRefundDetailModel.setCreateBy(-1L);
                mallOrderRefundDetailModel.setQuantity(cmsOrderApplyRefundDetailsVo.getQuantity());
                mallOrderRefundDetailModelList.add(mallOrderRefundDetailModel);
            }
            if (mallOrderRefundDetailModelList.size() > 0) {
                cmsMallOrderRefundDetailService.saveList(mallOrderRefundDetailModelList);
                for (MallOrderRefundDetailModel mallOrderRefundDetailModel1 : mallOrderRefundDetailModelList) {
                    MallOrderDetailModel mallOrderDetailModel = cmsOrderDetailService.getMallOrderDetailModelById(mallOrderRefundDetailModel1.getOrderDetailId());
                    ProcurementOrderDetailModel procurementOrderDetailModel = new ProcurementOrderDetailModel();
                    procurementOrderDetailModel.setProcurementStatus(4);
                    procurementOrderDetailModel.setProductQuantity(mallOrderDetailModel.getQuantity());
                    procurementOrderDetailModel.setProcurementQuantity(mallOrderDetailModel.getQuantity() - mallOrderRefundDetailModel1.getQuantity());
                    procurementOrderDetailModel.setFatherOrderCode(mallOrderModel.getParentOrderCode());
                    procurementOrderDetailModel.setSonOrderId(mallOrderModel.getId());
                    procurementOrderDetailModel.setSonOrderCode(mallOrderModel.getOrderCode());
                    procurementOrderDetailModel.setOrderDetailId(mallOrderRefundDetailModel1.getOrderDetailId());
                    procurementOrderDetailModel.setShopId(userSession.getShopId());
                    procurementOrderDetailModel.setProductId(mallOrderDetailModel.getProductId());
                    procurementOrderDetailModel.setProductSkuId(mallOrderDetailModel.getProductSkuId());
                    procurementOrderDetailModel.setCreateBy(userSession.getId());
                    procurementOrderDetailModel.setCreateTime(date);
                    procurementOrderDetailModel.setIsDelete(false);
                    cmsProcurementOrderDetailService.save(procurementOrderDetailModel);
                    mallOrderDetailModel.setIsOutStock(true);
                    cmsOrderDetailService.save(mallOrderDetailModel);
                }
            }
        }
        cmsOrderShopRefundLogService.save(orderShopRefundLogModel);//添加记录

        //修改子订单
        mallOrderModel.setRefundStatus(refundStatus);
        mallOrderModel.setLastUpdateTime(date);
        mallOrderModel.setLastUpdateBy(userSession.getId());
        save(mallOrderModel);
        MallOrderModel orderByOrderCode = getOrderByOrderCode(mallOrderModel.getParentOrderCode());
        if (orderByOrderCode == null) {
            throw new YiTaoCmsRuntimeException("无法获取订单信息");
        }
        //修改父订单
        orderByOrderCode.setLastUpdateBy(userSession.getId());
        orderByOrderCode.setLastUpdateTime(date);
        save(orderByOrderCode);
        return base.getSuccessMsg();
    }

    /**
     * 判断是否可以退款
     *
     * @param orderId 子订单ID
     * @return
     */
    private Integer isRefund(Long orderId) {
        MallOrderModel orderByOrderId = getOrderByOrderId(orderId);
        if (orderByOrderId.getRefundStatus() == null) {
            //同步以前数据
            orderByOrderId.setRefundStatus(OrderStatusEmnu.REFUND_STATUS.STANDARD_ORDER.getCode());
        }
        if (orderByOrderId.getRefundStatus() != null && !orderByOrderId.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.STANDARD_ORDER.getCode())) {
            //已经申请过退款记录  不可再次申请
            return BaseEnum.YesOrNoEnum.NO.getCode();
        }
        if (orderByOrderId.getOrderStatus().equals(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode())) {
            //取消订单无需退款
            return BaseEnum.YesOrNoEnum.NO.getCode();
        }
        if (orderByOrderId.getOrderStatus().equals(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode())) {
            //取消订单无需退款
            return BaseEnum.YesOrNoEnum.NO.getCode();
        }
        if (orderByOrderId.getPayStatus() == OrderStatusEmnu.PAY_STATUS.NOT_PAY.getCode()) {
            //未支付订单不需要退款
            return BaseEnum.YesOrNoEnum.NO.getCode();
        }
        return BaseEnum.YesOrNoEnum.YES.getCode();
    }

    /**
     * 退款商品数不能大于购买数
     *
     * @param cmsOrderApplyRefundDetailsVoList
     */
    private void verifyProductQuantity(List<CmsOrderApplyRefundDetailsVo> cmsOrderApplyRefundDetailsVoList) {
        if (cmsOrderApplyRefundDetailsVoList != null && cmsOrderApplyRefundDetailsVoList.size() > 0) {
            for (CmsOrderApplyRefundDetailsVo cmsOrderApplyRefundDetailsVo : cmsOrderApplyRefundDetailsVoList) {
                MallOrderDetailModel mallOrderDetailModel = cmsOrderDetailService.getMallOrderDetailModelById(cmsOrderApplyRefundDetailsVo.getId());
                if (mallOrderDetailModel == null) {
                    throw new YiTaoCmsRuntimeException("未查询到订单详情信息");
                }
                if (cmsOrderApplyRefundDetailsVo.getQuantity() == null || cmsOrderApplyRefundDetailsVo.getQuantity() < 1) {
                    throw new YiTaoCmsRuntimeException("退款商品个数不能为 0 ");
                }
                if (mallOrderDetailModel.getQuantity() < cmsOrderApplyRefundDetailsVo.getQuantity()) {
                    ProductInfoModel productInfoById = productCmsService.getProductInfoById(mallOrderDetailModel.getProductId());
                    throw new YiTaoCmsRuntimeException("商品 【" + productInfoById.getProductName() + "】 退款数量不能超过购买数量");
                }
            }
        }
    }

    public String getTongteExpressNumber(Long orderId) {
        MallOrderModel orderByOrderId = getOrderByOrderId(orderId);
        UserAddressManagementModel u = appUserAddressService.getUserAddressManagementModelById(orderByOrderId.getOrderDeliveryAddressId());
        Map<String, String> map = Maps.newConcurrentMap();
        Map<String, String> mapString = Maps.newConcurrentMap();
        StringBuffer goods = new StringBuffer();//商品名称
        StringBuffer nums = new StringBuffer();//数量
        StringBuffer qty = new StringBuffer();//品牌
        Set<Long> productIdList = Sets.newHashSet();
        List<MallOrderDetailModel> orderDetailModelListByOrderId = cmsOrderDetailService.getOrderDetailModelListByOrderId(orderByOrderId.getId());
        if (orderDetailModelListByOrderId != null && orderDetailModelListByOrderId.size() > 0) {
            for (MallOrderDetailModel mallOrderDetailModel : orderDetailModelListByOrderId) {
                if (mallOrderDetailModel.getLogisticStatus() != null) {
                    //商品已经发货
                    if (mallOrderDetailModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.SHIPPED.getCode()) || mallOrderDetailModel.getLogisticStatus().equals(OrderStatusEmnu.LOGISTIC_STATUS.HAVE_BEEN_SIGNED.getCode())) {
                        continue;
                    }
                }
                if (mallOrderDetailModel.getIsOutStock() != null && mallOrderDetailModel.getIsOutStock()) {
                    //查询缺货数量
                    ProcurementOrderDetailModel stockoutInfoByOrderDetailId = cmsProcurementOrderDetailService.getStockoutInfoByOrderDetailId(mallOrderDetailModel.getId());
                    if (stockoutInfoByOrderDetailId != null) {
                        Integer qutStockQuantity = stockoutInfoByOrderDetailId.getProductQuantity() - stockoutInfoByOrderDetailId.getProcurementQuantity();//缺货数量
                        if (qutStockQuantity >= mallOrderDetailModel.getQuantity()) {
                            //商品缺货不能发货;
                            continue;
                        }
                    }
                }
                productIdList.add(mallOrderDetailModel.getProductId());
                nums.append(mallOrderDetailModel.getQuantity()).append(",");
            }
        }
        for (Long productId : productIdList) {
            ProductInfoModel productInfoById = productCmsService.getProductInfoById(productId);
            goods.append(productInfoById.getProductName()).append(",");
            qty.append(productInfoById.getBrandName()).append(",");
        }
        mapString.put("AttnPerson", u.getNickName());
        mapString.put("AttnPhone", u.getPhone());
        mapString.put("AttnAddress", u.getProvince() + u.getCity() + u.getArea() + u.getAddress());
        mapString.put("IdCardNum", orderByOrderId.getBuyerCardNo());
        mapString.put("Goods", goods.substring(0, goods.length() - 1));
        mapString.put("Qty", nums.substring(0, nums.length() - 1));
        mapString.put("No", qty.substring(0, qty.length() - 1));
        map.put("token", "05582478");
        map.put("content", JSON.toJSONString(mapString));
        String string = "http://ex.tongtexpress.com/LxApi/AddWayBill";//+ "?token=" + "05582478" + "&" + "content=" + JSON.toJSONString(mapString);
        System.out.println(string);
        String post = HttpUtils.post(string, map);
        JSONObject jsonObject = JSON.parseObject(post);
        String message = jsonObject.getString("message");
        String providernum = jsonObject.getString("Providernum");
        Boolean b = jsonObject.getBoolean("b");
        if (!b) {
            throw new YiTaoCmsRuntimeException("获取通特快递单异常 错误" + message);
        }
        return providernum;
    }


    /**
     * 修改订单金额
     *
     * @param orderDetailId 订单详情ID
     * @param price         修改金额
     * @return
     */
    @Transactional
    public DataOutput updateOrderMoneyByOrderId(Long orderDetailId, Long price) {
        Date date = new Date();
        //判断用户是否登陆
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }
        MallOrderDetailModel mallOrderDetailModel = cmsOrderDetailService.getMallOrderDetailModelById(orderDetailId);
        if (mallOrderDetailModel == null) {
            return base.getErrorMsg();
        }
        MallOrderModel mallOrderModel = getOrderByOrderId(mallOrderDetailModel.getOrderId());
        //订单是否支付
        if (mallOrderModel.getPayStatus().equals(OrderStatusEmnu.PAY_STATUS.HAVE_PAY.getCode())) {
            return base.getErrorMsg("订单已支付不可修改价格");
        }
        if (mallOrderModel.getOrderStatus().equals(OrderStatusEmnu.ORDER_STATUS.CANCEL.getCode())) {
            return base.getErrorMsg("订单已取消不可修改价格");
        }
        List<MallOrderMoneyChangeLogModel> mallOrderMoneyChangeLogModels = cmsOrderMoneyChangeLogService.gMallOrderMoneyChangeLogByOrderId(mallOrderModel.getId());
        if (mallOrderMoneyChangeLogModels == null) {
            mallOrderMoneyChangeLogModels = Lists.newArrayList();
        }
        if (mallOrderMoneyChangeLogModels.size() > 0) {
            //  return base.getErrorMsg("订单价格已经变更不可多次变更");
        }
        //   优惠金额 = （商品实际金额 - 修改后的商品金额） *  商品数量
        ProductSkuModel productSkuDtoById = productCmsSkuService.getProductSkuDtoById(mallOrderDetailModel.getProductSkuId());
        Long favorableFee = (productSkuDtoById.getSalesPrice() - price) * mallOrderDetailModel.getQuantity();
        Long orderDetailFavorableFee = favorableFee;
        /*if (mallOrderDetailModel.getFavorableFee1() != null) {
            orderDetailFavorableFee = mallOrderDetailModel.getFavorableFee1() + orderDetailFavorableFee;
        }*/

        List<MallOrderDetailModel> mallOrderDetailModelList = newArrayList();
        mallOrderDetailModelList.add(mallOrderDetailModel);

        Long orderFavorableFee = favorableFee;
        List<MallOrderDetailModel> orderDetailModelListNotIn = cmsOrderDetailService.getOrderDetailModelListNotIn(mallOrderDetailModel.getOrderId(), mallOrderDetailModelList);
        for (MallOrderDetailModel mallOrderDetailModel1 : orderDetailModelListNotIn) {
            if (mallOrderDetailModel1.getFavorableFee1() != null) {
                orderFavorableFee += mallOrderDetailModel1.getFavorableFee1();
            }
        }
        //添加商品改价记录
        Long productEndAmount = price * mallOrderDetailModel.getQuantity();
        cmsOrderMoneyChangeLogService.saveMallOrderMoneyChangeLogModel(mallOrderModel,
                productEndAmount, userSession, date, mallOrderDetailModel.getId());
        //添加子订单记录
        Long sonOrderEndAmount = mallOrderModel.getOrderTotalAmount() - orderFavorableFee;// + (mallOrderModel.getFreightFee() == null ? 0L : mallOrderModel.getFreightFee());
        cmsOrderMoneyChangeLogService.saveMallOrderMoneyChangeLogModel(mallOrderModel,
                sonOrderEndAmount, userSession, date, null);
        //修改父亲订单记录
        MallOrderModel mallOrderModelByOrderCode = getOrderByOrderCode(mallOrderModel.getParentOrderCode());
        Long fatherOrderEndAmount = mallOrderModelByOrderCode.getOrderTotalAmount() - orderFavorableFee; //+ (mallOrderModelByOrderCode.getFreightFee() == null ? 0L : mallOrderModelByOrderCode.getFreightFee());
        cmsOrderMoneyChangeLogService.saveMallOrderMoneyChangeLogModel(mallOrderModelByOrderCode,
                fatherOrderEndAmount,
                userSession,
                date,
                null);
        mallOrderDetailModel.setLastUpdateTime(date);
        mallOrderDetailModel.setProductSalesPrice(price);
        mallOrderDetailModel.setFavorableFee1(orderDetailFavorableFee);
        mallOrderDetailModel.setBasePrice(price * mallOrderDetailModel.getQuantity());
        mallOrderDetailModel.setSharePrice(price * mallOrderDetailModel.getQuantity());
        MallOrderDetailModel mallOrderDetailModel1 = cmsOrderDetailService.save(mallOrderDetailModel);//修改订单商品金额
        List<MallOrderDetailModel> mallOrderDetailModelListById = cmsOrderDetailService.getChildItemTotalAmount(mallOrderDetailModel1.getOrderId(), mallOrderDetailModel1.getId());
        mallOrderDetailModelListById.add(mallOrderDetailModel1);
        //子订单
        Long childItemTotalAmount = 0L;
        for (MallOrderDetailModel mallOrderDetailModel2 : mallOrderDetailModelListById) {//计算商品总金额
            childItemTotalAmount += mallOrderDetailModel2.getBasePrice();
        }
        Long sonOrderFavorableFee = mallOrderModel.getFavorableFee1() == null ? favorableFee : /*mallOrderModel.getFavorableFee1() +*/ favorableFee;///优惠金额
        MallOrderModel save = saveMallOrderModel(mallOrderModel, childItemTotalAmount, fatherOrderEndAmount, sonOrderFavorableFee, date);//修改子订单金额
        //父订单
        List<MallOrderModel> fetch = queryFactory.select(Q).from(Q).where(Q.parentOrderCode.eq(mallOrderModelByOrderCode.getOrderCode()).and(Q.id.notIn(save.getId()))).fetch();
        fetch.add(save);
        Long itemTotalAmount = 0L;
        for (MallOrderModel mallOrderModel1 : fetch) {//计算商品总金额
            itemTotalAmount += mallOrderModel1.getItemTotalAmount();
        }
        Long fatherOrderFavorableFee = mallOrderModelByOrderCode.getFavorableFee1() == null ? favorableFee : /*mallOrderModelByOrderCode.getFavorableFee1() +*/ favorableFee;
        saveMallOrderModel(mallOrderModelByOrderCode, itemTotalAmount, fatherOrderEndAmount, fatherOrderFavorableFee, date);//修改父订单金额
        return base.getSuccessMsg();
    }


    /**
     * 修改订单金额
     *
     * @param mallOrderModel       订单信息
     * @param itemTotalAmount      商品金额
     * @param fatherOrderEndAmount 修改后的金额
     * @param favorableFee1        优惠金额
     * @param date                 修改时间
     * @return
     */
    @Transactional
    public MallOrderModel saveMallOrderModel(MallOrderModel mallOrderModel, Long itemTotalAmount, Long fatherOrderEndAmount, Long favorableFee1, Date date) {
        mallOrderModel.setItemTotalAmount(itemTotalAmount);//商品总金额
        mallOrderModel.setActualAmount(fatherOrderEndAmount);//父订单修改后的金额
        mallOrderModel.setFavorableFee1(favorableFee1);
        mallOrderModel.setLastUpdateTime(date);
        return save(mallOrderModel);
    }

    public DataOutput addRemark(Long orderId, String remark) {
        MallOrderModel orderByOrderId = getOrderByOrderId(orderId);
        redisUtil.setStr(orderByOrderId.getOrderCode(), remark);
        Map<String, String> map = Maps.newConcurrentMap();
        map.put("remark", remark);
        return base.getSuccessMsg(map);
    }

    public DataOutput getRemark(Long orderId) {
        MallOrderModel orderByOrderId = getOrderByOrderId(orderId);
        String remark = redisUtil.getStr(orderByOrderId.getOrderCode());
        if (remark == null) {
            remark = "";
        }
        Map<String, String> map = Maps.newConcurrentMap();
        map.put("remark", remark);
        return base.getSuccessMsg(map);
    }

    @Transactional
    public DataOutput getOrderImporByJinCheng(MultipartFile file, OperationUserCmsModel userSession, HttpServletRequest request) {
        List<OrderExcelVo> orderExcelVoList = Lists.newArrayList();
        Sheet rows = ExcelExportUtil.orderImport(file);
        for (int i = 1; i <= rows.getLastRowNum(); i++) {
            Row row = rows.getRow(i);//获取第i行数据
            if (StringUtils.isEmpty(ExcelExportUtil.cellType(row.getCell(29)))) {
                break;
            }
            OrderExcelVo orderExcelVo = new OrderExcelVo();
            String orderCode = ExcelExportUtil.cellType(row.getCell(0)).trim();
            orderExcelVo.setOrderCode(orderCode);
            String logistics = ExcelExportUtil.cellType(row.getCell(1));
            if (logistics != null) {
                logistics = logistics.trim();
                logistics.matches("[0-9]+");
                if (!StringUtils.isEmpty(logistics)) {
                    boolean matches = logistics.matches("[0-9]+");
                    ServicesCompanyInfoModel servicesCompanyInfoModelById = null;
                    if (matches) {
                        servicesCompanyInfoModelById = cmsServicesCompanyInfoService.getServicesCompanyInfoModelById(Long.valueOf(logistics));
                    }
                    if (!matches && servicesCompanyInfoModelById == null) {
                        servicesCompanyInfoModelById = cmsServicesCompanyInfoService.getServicesCompanyInfoByNameabbr(logistics);
                    }
                    if (servicesCompanyInfoModelById == null) {
                        return base.getErrorMsg("物流公司参数 = 【" + logistics + "】 查询不到物流信息请确认");
                    }
                    orderExcelVo.setLogistics(servicesCompanyInfoModelById.getId().toString());
                    orderExcelVo.setLogisticsCode(servicesCompanyInfoModelById.getNameAbbr());
                    orderExcelVo.setLogisticsName(servicesCompanyInfoModelById.getCompanyName());
                    //     orderExcelVo.setLogistics(ExcelExportUtil.cellType(row.getCell(2)).trim());      //物流公司
                }
            }
            String logisticsNo = ExcelExportUtil.cellType(row.getCell(2));
            if (!StringUtils.isBlank(logisticsNo)) {
                orderExcelVo.setLogisticsNo(logisticsNo.trim());
            }
            /*
            orderExcelVo.setChannel(ExcelExportUtil.cellType(row.getCell(6)).trim());//渠道
            orderExcelVo.setShipperName(ExcelExportUtil.cellType(row.getCell(4)).trim());//寄件人姓名
            orderExcelVo.setShipperphone(ExcelExportUtil.cellType(row.getCell(5)).trim());//寄件人电话
            orderExcelVo.setBrandName(ExcelExportUtil.cellType(row.getCell(6)).trim()); //品牌
            orderExcelVo.setChineseName(ExcelExportUtil.cellType(row.getCell(7)).trim());  //中文品名 商品名+sku值
            */
            /*String quantity = ExcelExportUtil.cellType(row.getCell(8)).trim(); //数量
            if (!StringUtils.isEmpty(quantity)) {
                orderExcelVo.setQuantity(Integer.valueOf(quantity));
            }*/
            //单价
         /*   String salesPrice = ExcelExportUtil.cellType(row.getCell(9)).trim();
            if (salesPrice != null) {
                orderExcelVo.setSalesPrice(new BigDecimal(Double));
            }*/
            //规格
            //private String specification;//空 10
            //单位
            //private String units; //空11
            //包裹重量
            //private Double weight; //空12
            //保险额
            //private BigDecimal insurance;//空13
            //保险费
            //rivate BigDecimal premium;//空14
            //关税
            //private BigDecimal tariff;//空15
            //收件人名称
            //private String nickName;//16
            //收件人电话
            //private String phone;17
            //收件人省
            //private String province;18
            //收件人城市
            //private String city;19
            //收件人区
            //private String area;20
            //收件人具体地址
            //private String address;21
            //收件人邮编
            //private String recipientZipCode;//空22
            //收件人身份证号码
            //private String cardNo;//23
            //国内转运公司
            //private String transshipmentCompany;//空24
            //国内转运单号
            //private String transhipmentOrderNo;//空25
            //电商订单号
            // String orderCode = ExcelExportUtil.cellType(row.getCell(26)).trim();//订单id
          /*  if (orderCode == null) {
                return base.getErrorMsg(" 第" + i + "行 查询不到订单编号不完整请确认参数是否正确");
            }*/
            if (StringUtils.isNotEmpty(orderCode)) {
                MallOrderModel orderByOrderCode = getOrderByOrderCode(orderCode);
                if (orderByOrderCode == null) {
                    return base.getErrorMsg(" 第" + i + "行 订单编号【" + orderCode + "】  查询不到订单信息请确认参数是否正确");
                }
                if (!orderByOrderCode.getShopId().equals(userSession.getShopId())) {
                    return base.getErrorMsg(" 第" + i + "行 订单信息不属于您  无权限修改");
                }
            }
            orderExcelVo.setOrderCode(orderCode);
            String skuCode = ExcelExportUtil.cellType(row.getCell(29));
            ProductSkuModel productCmsSku = productCmsSkuService.getProductCmsSku(skuCode);
            if (productCmsSku == null) {
                return base.getErrorMsg(" 第" + i + "行 商品SKU编号【" + skuCode + "】  查询不到订单信息请确认参数是否正确");
            }
            if (skuCode == null) {
                return base.getErrorMsg(" 第" + i + "行 查询不到商品SKU不完整请确认参数是否正确");
            }
            orderExcelVo.setSkuCode(skuCode);
            orderExcelVoList.add(orderExcelVo);
        }
        if (orderExcelVoList.size() <= 0) {
            return base.getSuccessMsg();
        }
        //执行update操作
        updateOrderImporInfo(orderExcelVoList, userSession);

        return base.getSuccessMsg();
    }


    @Transactional
    public String addShopUserGrad(Date date) {
        String constantDataModelById = constantDataService.getConstantDataModelById(601L);
        Boolean aBoolean = Boolean.valueOf(constantDataModelById);
        if (!aBoolean) {
            return "";
        }
        List<OrderShopAndUserVo> orderShopAndUserVoList = orderMapper.getGroupByUserIdAndShopId();
        logger.info("Order GroupBy UserId And ShopId 【{}】", JacksonUtils.toJson(orderShopAndUserVoList));
        List<ShopUserGradeModel> shopUserGradeModelList = Lists.newArrayList();
        if (orderShopAndUserVoList != null && orderShopAndUserVoList.size() > 1) {
            ShopUserGradeModel shopUserGradeModel = null;
            for (OrderShopAndUserVo orderShopAndUserVo : orderShopAndUserVoList) {
                shopUserGradeModel = shopUserGradeService.getShopUserGradeModelByShopIdAndUserId(orderShopAndUserVo.getShopId(), orderShopAndUserVo.getUserId());
                if (shopUserGradeModel != null) {
                    continue;
                }
                shopUserGradeModel = new ShopUserGradeModel();
                shopUserGradeModel.setCreateTime(date);
                shopUserGradeModel.setDeleteStatus(Boolean.FALSE);
                shopUserGradeModel.setShopId(orderShopAndUserVo.getShopId());
                shopUserGradeModel.setUserId(orderShopAndUserVo.getUserId());
                UserInfoModel userInfoModel = appUserService.getAppUserInfoByUserId(orderShopAndUserVo.getUserId());
                if (userInfoModel == null) {
                    continue;
                }
                shopUserGradeModel.setRegTime(userInfoModel.getRegisterTime());
                shopUserGradeModel.setPhone(userInfoModel.getPhone());
                shopUserGradeModel.setUserGrade(0);
                shopUserGradeModelList.add(shopUserGradeModel);
            }
        }
        logger.info("ShopUserGradeModelList 【{}】", JacksonUtils.toJson(shopUserGradeModelList));
        if (shopUserGradeModelList.size() > 0) {
            shopUserGradeService.saveShopUserGradeModelList(shopUserGradeModelList);
        }
        return null;
    }

    public DataOutput getPayType() {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        List<CategoryVo> categoryVoList = Lists.newArrayList();
        List<Integer> payClientTypeList = newArrayList();
        CategoryVo categoryVo1 = new CategoryVo();
        /**
         * 添加默认的
         */
        categoryVo1.setValue(OrderEnums.PayTypeName.DEFAULT.getName());
        categoryVo1.setKey(OrderEnums.PayTypeName.DEFAULT.getCode());
        categoryVoList.add(categoryVo1);
        /**
         * 微信
         */
        payClientTypeList.add(PayEnum.PAY_CLIENT_TYPE.WE_CHAT.getCode());
        payClientTypeList.add(PayEnum.PAY_CLIENT_TYPE.HF_WE_CHAT.getCode());
        payClientTypeList.add(PayEnum.PAY_CLIENT_TYPE.UMF_WE_CHAT.getCode());
        List<PayStreamModel> payStreamInfoByPayClientTypeList = cmsPayStreamService.getPayStreamInfoByPayClientTypeList(payClientTypeList, userSession.getShopId());
        if (payStreamInfoByPayClientTypeList != null && payStreamInfoByPayClientTypeList.size() > 0) {
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setValue(OrderEnums.PayTypeName.WECHAT.getName());
            categoryVo.setKey(OrderEnums.PayTypeName.WECHAT.getCode());
            categoryVoList.add(categoryVo);
        }

        /**
         * 支付宝
         */
        payClientTypeList = newArrayList();
        payClientTypeList.add(PayEnum.PAY_CLIENT_TYPE.LL_PAY.getCode());
        payClientTypeList.add(PayEnum.PAY_CLIENT_TYPE.HF_CARD_PAY.getCode());
        payClientTypeList.add(PayEnum.PAY_CLIENT_TYPE.UMF_CARD_PAY.getCode());
        payStreamInfoByPayClientTypeList = cmsPayStreamService.getPayStreamInfoByPayClientTypeList(payClientTypeList, userSession.getShopId());
        if (payStreamInfoByPayClientTypeList != null && payStreamInfoByPayClientTypeList.size() > 0) {
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setValue(OrderEnums.PayTypeName.BANK_CARD.getName());
            categoryVo.setKey(OrderEnums.PayTypeName.BANK_CARD.getCode());
            categoryVoList.add(categoryVo);
        }
        /**
         * 线下
         */
        payClientTypeList = newArrayList();
        payClientTypeList.add(PayEnum.PAY_CLIENT_TYPE.OFFLINE_PAY.getCode());
        payStreamInfoByPayClientTypeList = cmsPayStreamService.getPayStreamInfoByPayClientTypeList(payClientTypeList, userSession.getShopId());
        if (payStreamInfoByPayClientTypeList != null && payStreamInfoByPayClientTypeList.size() > 0) {
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setValue(OrderEnums.PayTypeName.OFFLINE.getName());
            categoryVo.setKey(OrderEnums.PayTypeName.OFFLINE.getCode());
            categoryVoList.add(categoryVo);
        }

        return base.getSuccessMsg(categoryVoList);
    }

    public DataOutput<CategoryVo> getAfterSaleOrderStatus(Long afterSaleId) {
        MallOrderRefundModel mallOrderRefundModelByAfterSaleId = cmsMallOrderRefundService.getMallOrderRefundModelByAfterSaleId(afterSaleId);
        List<CategoryVo> categoryVoList = Lists.newArrayList();
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setKey(OrderEnums.RefundStatusEnums.CANCELED.getCode());
        categoryVo.setValue(OrderEnums.RefundStatusEnums.CANCELED.getName());
        categoryVoList.add(categoryVo);
        if (afterSaleId == null) {
            categoryVo = new CategoryVo();
            categoryVo.setKey(OrderEnums.RefundStatusEnums.REFUND_FINISHED.getCode());
            categoryVo.setValue(OrderEnums.RefundStatusEnums.REFUND_FINISHED.getName());
            categoryVoList.add(categoryVo);
        }
        MallOrderModel orderByOrderId = getOrderByOrderId(mallOrderRefundModelByAfterSaleId.getOrderId());
        if (orderByOrderId == null) {
            return base.getErrorMsg("未查询到订单");
        }
        /**
         * 配置退款按钮
         */
        MallOrderModel orderByOrderCode = getOrderByOrderCode(orderByOrderId.getParentOrderCode());
        PayStreamModel payStreamInfoByOrderId = cmsPayStreamService.getPayStreamInfoByOrderId(orderByOrderCode.getId());
        if (payStreamInfoByOrderId.getPayClientType().equals(8)) {
            categoryVo = new CategoryVo();
            categoryVo.setKey(OrderEnums.RefundStatusEnums.OFFLINE_REFUND.getCode());
            categoryVo.setValue(OrderEnums.RefundStatusEnums.OFFLINE_REFUND.getName());
            categoryVoList.add(categoryVo);
        } else {
            categoryVo = new CategoryVo();
            categoryVo.setKey(OrderEnums.RefundStatusEnums.REFUND_FINISHED.getCode());
            categoryVo.setValue(OrderEnums.RefundStatusEnums.REFUND_FINISHED.getName());
            categoryVoList.add(categoryVo);
        }
        return base.getSuccessMsg(categoryVoList);
    }

    public DataOutput<List<OrderLogisticsList>> getPackageList(Long orderId) {
        List<OrderLogisticsList> orderLogisticsListArrayList = newArrayList();
        List<MallOrderDeliveryModel> mallOrderDeliveryModelByOrderId = cmsOrderDeliveryService.getMallOrderDeliveryModelByOrderId(orderId);
        if (mallOrderDeliveryModelByOrderId == null) {
            return base.getSuccessMsg(orderLogisticsListArrayList);
        }
        /**
         * 查询全部的商品信息
         */
        OrderLogisticsList orderLogisticsList = null;
        for (MallOrderDeliveryModel mallOrderDeliveryModel : mallOrderDeliveryModelByOrderId) {
            orderLogisticsList = new OrderLogisticsList();
            BeanUtils.copyProperties(mallOrderDeliveryModel, orderLogisticsList);
            List<OrderDeliveryPackageModel> orderPackageInfo = orderDeliveryPackageService.getOrderPackageInfo(mallOrderDeliveryModel.getId());
            if (orderPackageInfo == null || orderPackageInfo.size() < 1) {
                /**
                 * 冗余以前订单的数据  最开始是没有包裹的
                 */
                orderLogisticsList.setCmsMallOrderDetailVoList(cmsOrderDetailService.getMallOrderDetailDto(mallOrderDeliveryModel.getOrderId()));
            } else {
                /**
                 * 查询包裹里面商品跟商品数量
                 */
                List<CmsMallOrderDetailVo> cmsMallOrderDetailVos = Lists.newArrayList();
                CmsMallOrderDetailVo cmsMallOrderDetailVo = null;
                for (OrderDeliveryPackageModel orderDeliveryPackageModel : orderPackageInfo) {
                    cmsMallOrderDetailVo = new CmsMallOrderDetailVo();
                    MallOrderDetailModel mallOrderDetailModelById = cmsOrderDetailService.getMallOrderDetailModelById(orderDeliveryPackageModel.getOrderDetailId());
                    BeanUtils.copyProperties(mallOrderDetailModelById, cmsMallOrderDetailVo);
                    if (mallOrderDetailModelById.getIsOutStock() == null || mallOrderDetailModelById.getIsOutStock() == false) {
                        cmsMallOrderDetailVo.setQuantity(mallOrderDetailModelById.getQuantity());
                    } else {
                        ProcurementOrderDetailModel stockoutInfoByOrderDetailId = cmsProcurementOrderDetailService.getStockoutInfoByOrderDetailId(mallOrderDetailModelById.getId());
                        if (stockoutInfoByOrderDetailId != null) {
                            cmsMallOrderDetailVo.setQuantity(mallOrderDetailModelById.getQuantity() - (stockoutInfoByOrderDetailId.getProcurementQuantity() == null ? 0 : stockoutInfoByOrderDetailId.getProcurementQuantity()));
                        } else {
                            cmsMallOrderDetailVo.setQuantity(mallOrderDetailModelById.getQuantity());
                        }
                    }

                    if (mallOrderDetailModelById.getProductId() != null) {
                        ProductInfoModel productInfoModel = productCmsService.getProductInfoById(mallOrderDetailModelById.getProductId());
                        if (productInfoModel != null) {
                            cmsMallOrderDetailVo.setProductImgUrl(productInfoModel.getProductMainImgUrl());
                            cmsMallOrderDetailVo.setProductCode(productInfoModel.getProductCode());
                            cmsMallOrderDetailVo.setProductName(productInfoModel.getProductName());
                            cmsMallOrderDetailVo.setFreightFee(productInfoModel.getFreightFee());
                            if (mallOrderDetailModelById.getProductSkuId() != null) {
                                ProductSkuModel productSkuModel = productCmsSkuService.getProductSkuDtoById(mallOrderDetailModelById.getProductSkuId());
                                if (productSkuModel != null) {
                                    StringBuffer sb = new StringBuffer();
                                /*if (productSkuModel.getAttrSpecName() != null) {
                                    sb.append(productSkuModel.getAttrSpecName());
                                }*/
                                    if (productSkuModel.getParentId() != null) {
                                        ProductSkuModel productParentSkuModel = productCmsSkuService.getProductSkuDtoById(productSkuModel.getParentId());
                                        if (productParentSkuModel != null && StringUtils.isNotEmpty(productParentSkuModel.getAttrSpecValue())) {
                                            sb.append(productParentSkuModel.getAttrSpecName()).append(":").append(productParentSkuModel.getAttrSpecValue()).append("  ");
                                        }
                                    }
                                    if (productSkuModel.getAttrSpecValue() != null) {
                                        /* sb.append("/").*/
                                        sb.append(productSkuModel.getAttrSpecName()).append(":").append(productSkuModel.getAttrSpecValue());
                                    }
                                    cmsMallOrderDetailVo.setProductSkuName(sb.toString());
                                }
                            }
                        }
                    }
                    cmsMallOrderDetailVos.add(cmsMallOrderDetailVo);
                }
                orderLogisticsList.setCmsMallOrderDetailVoList(cmsMallOrderDetailVos);
            }
            orderLogisticsListArrayList.add(orderLogisticsList);
        }
        return base.getSuccessMsg(orderLogisticsListArrayList);
    }

    @Transactional
    public DataOutput updateDeliveryNo(Long deliveryId, String expressNumber, Integer expressCode) {
        Date date = new Date();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        MallOrderDeliveryModel mallOrderDeliveryModel = cmsOrderDeliveryService.getMallOrderDeliveryById(deliveryId);
        MallOrderModel orderByOrderId = getOrderByOrderId(mallOrderDeliveryModel.getOrderId());
        ServicesCompanyInfoModel servicesCompanyInfoModelById = cmsServicesCompanyInfoService.getServicesCompanyInfoModelById(Long.valueOf(expressCode));

        if (servicesCompanyInfoModelById == null) {
            return base.getErrorMsg("查询不到物流公司信息请重新确认");
        }


        /**
         * 添加修改记录表
         */
        OrderDeliveryUpdateLogModel orderDeliveryUpdateLogModel = new OrderDeliveryUpdateLogModel();
        orderDeliveryUpdateLogModel.setCreateBy(userSession.getId());
        orderDeliveryUpdateLogModel.setCreatePhone(userSession.getPhone());
        orderDeliveryUpdateLogModel.setCreateTime(new Date());
        orderDeliveryUpdateLogModel.setIsDelete(false);
        orderDeliveryUpdateLogModel.setOrderDeliveryId(mallOrderDeliveryModel.getId());
        orderDeliveryUpdateLogModel.setShopId(orderByOrderId.getShopId());
        /**
         * 新的物流信息
         */
        orderDeliveryUpdateLogModel.setNewDeliveryCompanyCode(servicesCompanyInfoModelById.getNameAbbr());
        orderDeliveryUpdateLogModel.setNewDeliveryCompanyName(servicesCompanyInfoModelById.getCompanyName());
        orderDeliveryUpdateLogModel.setNewDeliveryNo(expressNumber);
        /**
         * 老的物流信息
         */
        orderDeliveryUpdateLogModel.setOldDeliveryCompanyCode(mallOrderDeliveryModel.getDeliveryCompanyCode());
        orderDeliveryUpdateLogModel.setOldDeliveryCompanyName(mallOrderDeliveryModel.getDeliveryCompanyName());
        orderDeliveryUpdateLogModel.setOldDeliveryNo(mallOrderDeliveryModel.getDeliveryNo());
        orderDeliveryUpdateLogModel.setOrderId(orderByOrderId.getId());
        orderDeliveryUpdateLogModel.setOrderCode(orderByOrderId.getOrderCode());
        orderDeliveryUpdateLogService.save(orderDeliveryUpdateLogModel);
        /**
         * 修改物流信息
         */
        mallOrderDeliveryModel.setDeliveryCompanyCode(servicesCompanyInfoModelById.getNameAbbr());
        mallOrderDeliveryModel.setDeliveryCompanyName(servicesCompanyInfoModelById.getCompanyName());
        if (StringUtils.isNotBlank(expressNumber)) {
            expressNumber = expressNumber.trim();
        }
        mallOrderDeliveryModel.setDeliveryNo(expressNumber);
        mallOrderDeliveryModel.setLastUpdateBy(userSession.getId());
        mallOrderDeliveryModel.setLastUpdateTime(date);
        cmsOrderDeliveryService.save(mallOrderDeliveryModel);

        UserAddressManagementModel userAddressManagementModelById = appUserAddressService.getUserAddressManagementModelById(orderByOrderId.getOrderDeliveryAddressId());
        // TODO 新版发货订阅
        if (kuaidi100Status) {
            if (servicesCompanyInfoModelById.getJoinedType() == null || servicesCompanyInfoModelById.getJoinedType() == 1) {
                kuaidi100CmsService.subscribeData(mallOrderDeliveryModel.getDeliveryCompanyCode(), mallOrderDeliveryModel.getDeliveryNo(), userAddressManagementModelById.getPhone());
            }
        }
        return base.getSuccessMsg();
    }


    @Transactional
    public String updateRefundByOrderCode(Long orderId, Long refundAmt, Date date) {
        String paySeq = "线下退款";//快照
        MallOrderModel mallOrderByCode = getOrderByOrderId(orderId);
        MallOrderModel parentOrder = getOrderByOrderCode(mallOrderByCode.getParentOrderCode());
        if (mallOrderByCode.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.REFUND.getCode()) ||
                mallOrderByCode.getRefundStatus().equals(OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND.getCode())) {
            logger.info("回调已消费 直接返回 order_id = [{}]", orderId);
            return null;
        }
        PayStreamModel getPayStreamModel = cmsPayStreamService.getPayStreamInfoByOrderId(parentOrder.getId());

        // 获取当前退款的是哪个订单，根据原表中的支付(收款)流水号查询
        PayStreamModel payStreamModel = new PayStreamModel();
        payStreamModel.setBusinessType(PayEnum.BUSINESS_TYPE_ENUM.MALL.getCode()); // 业务类型
        payStreamModel.setPayClientType(getPayStreamModel.getPayClientType()); // 支付类型
        payStreamModel.setPayType(PayEnum.PAY_TYPE_ENUM.USER_REFUND.getCode()); // 用户退款
        payStreamModel.setOrderId(mallOrderByCode.getId()); // 订单号
        payStreamModel.setOrderCode(parentOrder.getOrderCode()); // 订单code
        payStreamModel.setUserId(mallOrderByCode.getBuyerUserId()); // 下单人id
        payStreamModel.setPayTradeNo(System.currentTimeMillis() + ""); // 退款流水号
        // payStreamModel.setNoRefund(tradeNo); // 商户退款流水号
        payStreamModel.setPayCashFee(Long.valueOf(refundAmt)); // 退款金额
        Integer refundStatus = 0;
        if ("0000".equals("0000")) {
            // 判断这个订单是整单退款还是缺货退款
            if (parentOrder != null) {
                logger.info("当前退款状态" + parentOrder.getRefundStatus());
                if (OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND_OF.getCode().equals(parentOrder.getRefundStatus())) {
                    // 部分退款
                    refundStatus = OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND.getCode(); // 部分退款
                } else {
                    // 整单退款
                    refundStatus = OrderStatusEmnu.REFUND_STATUS.REFUND.getCode(); // 整单退款
                    /**
                     * 查询是否有优惠券 有的退券
                     */
                    refundVoucher(mallOrderByCode);
                }
            }
        } else {
            // 判断这个订单是整单退款还是缺货退款
            refundStatus = OrderStatusEmnu.REFUND_STATUS.REFUND_ERROR.getCode();
        }
        payStreamModel.setPayStatus(refundStatus); // 已退款
        payStreamModel.setPayData(paySeq);
        payStreamModel.setPayTime(date); // 退款时间
        payStreamModel.setCreateTime(date);
        cmsPayStreamService.save(payStreamModel);
        List<MallOrderModel> mallOrderByParentCode = getMallOrderModelByParentOrderCode(parentOrder.getOrderCode());
        Long childOrderId = mallOrderByParentCode.get(0).getId();
        updateOrderRefundStatusById(parentOrder.getOrderCode(), childOrderId, refundStatus); // 修改订单表和订单详情表退款状态
        cmsMallOrderRefundService.updateRefundStatusByOrderId(childOrderId, refundStatus); // 修改退款表信息
        if (OrderStatusEmnu.REFUND_STATUS.PORTION_REFUND_OF.getCode().equals(parentOrder.getRefundStatus())) {
            // 如果为部分退款，将缺货信息写入到日志表
            // 由于一个订单只能申请一次退款，订单详情id可以根据退款申请记录获取
            MallOrderRefundModel orderRefundByOrderId = cmsMallOrderRefundService.findOrderRefundByOrderId(childOrderId);
            if (orderRefundByOrderId != null) {
                // 根据退款记录id获取缺货退款详情
                List<MallOrderRefundDetailModel> byRefundId = cmsMallOrderRefundDetailService.findByRefundId(childOrderId);
                if (!CollectionUtils.isEmpty(byRefundId)) {
                    outStockRefundLogService.saveBatch(byRefundId, childOrderId, refundStatus, payStreamModel.getPayTradeNo());
                }
            }
        }
        return null;
    }

    @Transactional
    public int updateOrderRefundStatusById(String orderCode, Long orderId, Integer refundStatus) {
        // 获取这个订单的父订单
        MallOrderModel mallOrderModel = getOrderByOrderCode(orderCode);
        if (refundStatus == 0) {
            return 0;
        }
        int flag = repository.updateByWhere(Q.id.eq(mallOrderModel.getId()),
                it -> it.set(Q.refundStatus, refundStatus));
        //修改这个申请退款子订单
        if (flag > 0) {
            flag += repository.updateByWhere(PredicateBuilder.conjunction()
                    .and(() -> Q.id.eq(orderId)).get(), it -> it.set(Q.refundStatus, refundStatus));
            // 修改订单详情表
            flag = cmsOrderDetailService.updateRefundStatus(orderId, refundStatus);
        }
        return flag;
    }
}


